public void TestFeatureGeneration() {
            var fg = new PreviousMapFeatureGenerator();

            var sentence = new[] {"a", "b", "c"};

            var features = new List<string>();

            // this should generate the pd=null feature
            fg.CreateFeatures(features, sentence, 0, null);
            Assert.AreEqual(1, features.Count);
            Assert.AreEqual("pd=null", features[0]);

            features.Clear();

            // this should generate the pd=1 feature
            fg.UpdateAdaptiveData(sentence, new[] {"1", "2", "3"});
            fg.CreateFeatures(features, sentence, 0, null);
            Assert.AreEqual(1, features.Count);
            Assert.AreEqual("pd=1", features[0]);

            features.Clear();

            // this should generate the pd=null feature again after
            // the adaptive data was cleared
            fg.ClearAdaptiveData();
            fg.CreateFeatures(features, sentence, 0, null);
            Assert.AreEqual(1, features.Count);
            Assert.AreEqual("pd=null", features[0]);
        }
Exemplo n.º 2
0
 public void findNeigboursForNodeBorderCasesTest()
 {
     testNetwork.initialize (3, 3);
     map = testNetworkProbe.getField ("networkMap") as NodeController[,];
     List<Vector2> neighbourList = new List<Vector2> ();
     INode testNode = map [0, 0];
     MethodInfo findNeigboursForNode = testNetworkProbe.getMethod ("findNeigboursForNode");
     findNeigboursForNode.Invoke(testNetwork, new object[]{testNode,neighbourList});
     Assert.AreNotEqual(0,neighbourList.Count);
     Assert.AreEqual (3, neighbourList.Count);
     //Mid left
     neighbourList.Clear ();
     testNode = map [0, 1];
     findNeigboursForNode.Invoke(testNetwork, new object[]{testNode,neighbourList});
     Assert.AreEqual (5, neighbourList.Count);
     //Top Mid
     neighbourList.Clear ();
     testNode = map [1, 2];
     findNeigboursForNode.Invoke(testNetwork, new object[]{testNode,neighbourList});
     Assert.AreEqual (5, neighbourList.Count);
     //Top Right
     testNode = map [2, 2];
     findNeigboursForNode.Invoke(testNetwork, new object[]{testNode,neighbourList});
     Assert.AreEqual (3, neighbourList.Count);
 }
Exemplo n.º 3
0
		public void Constructor_Exceptions ()
		{
			HostFileChangeMonitor monitor;
			string relPath = Path.Combine ("relative", "file", "path");
			var paths = new List<string> {
				relPath
			};

			AssertExtensions.Throws<ArgumentException> (() => {
				monitor = new HostFileChangeMonitor (paths);
			}, "#A1");

			paths.Clear ();
			paths.Add (null);
			AssertExtensions.Throws<ArgumentException> (() => {
				monitor = new HostFileChangeMonitor (paths);
			}, "#A2");

			paths.Clear ();
			paths.Add (String.Empty);
			AssertExtensions.Throws<ArgumentException> (() => {
				monitor = new HostFileChangeMonitor (paths);
			}, "#A3");

			AssertExtensions.Throws<ArgumentNullException> (() => {
				monitor = new HostFileChangeMonitor (null);
			}, "#A4");

			paths.Clear ();
			AssertExtensions.Throws<ArgumentException> (() => {
				monitor = new HostFileChangeMonitor (paths);
			}, "#A5");
		}
        public void Join_with_multiple_correlationIds()
        {
            var sut = new ManualResetJoin(2);

            var results = new List<List<object>>();
            Action<List<object>> onJoin = results.Add;

            var corrId1 = Guid.NewGuid();
            var corrId2 = Guid.NewGuid();

            sut.Process(0, "a1", corrId1, onJoin);
            sut.Process(0, "x1", corrId2, onJoin);
            sut.Process(1, "b1", corrId1, onJoin);
            Assert.That(new object[] { new object[] { "a1", "b1" } }, Is.EqualTo(results));
            results.Clear();

            sut.Process(1, "y1", corrId2, onJoin);
            Assert.That(new object[] { new object[] { "x1", "y1" } }, Is.EqualTo(results));
            results.Clear();

            sut.Process(1, "b2", corrId1, onJoin);
            Assert.That(new object[] { new object[] { "a1", "b2" } }, Is.EqualTo(results));
            results.Clear();

            sut.Reset(corrId2);
            sut.Process(0, "s1", corrId2, onJoin);
            sut.Process(1, "t1", corrId2, onJoin);
            Assert.That(new object[] { new object[] { "s1", "t1" } }, Is.EqualTo(results));
        }
        public void Can_Mock_UploadFile()
        {
            string tempTextPath = Path.Combine (Path.GetTempPath (), "test.txt");
            using (File.CreateText(tempTextPath)){}

            var fileNamesUploaded = new List<string>();
            using (new HttpResultsFilter
            {
                UploadFileFn = (webReq, stream, fileName) => fileNamesUploaded.Add(fileName)
            })
            {
                ExampleGoogleUrl.PostFileToUrl(new FileInfo(tempTextPath), "text/plain");
                Assert.That(fileNamesUploaded, Is.EquivalentTo(new[] { "test.txt" }));

                fileNamesUploaded.Clear();

                ExampleGoogleUrl.PutFileToUrl(new FileInfo(tempTextPath), "text/plain");
                Assert.That(fileNamesUploaded, Is.EquivalentTo(new[] { "test.txt" }));

                fileNamesUploaded.Clear();

                var webReq = WebRequest.Create(ExampleGoogleUrl);
                webReq.UploadFile(new FileInfo(tempTextPath), "text/plain");
                Assert.That(fileNamesUploaded, Is.EquivalentTo(new[] { "test.txt" }));
            }
        }
Exemplo n.º 6
0
        public void Find()
        {
            var list = new List<int>();
            list.AddRange(new[] { 3, 4, 76, 34, 50, 23, 45 });

            var visitor = new ComparableFindingVisitor<int>(50);

            list.AcceptVisitor(visitor);
            Assert.IsTrue(visitor.Found);
            Assert.IsTrue(visitor.HasCompleted);

            visitor = new ComparableFindingVisitor<int>(50);
            list.Clear();
            list.AddRange(new[] { 50, 3, 4, 76, 34, 23, 45 });

            list.AcceptVisitor(visitor);
            Assert.IsTrue(visitor.Found);
            Assert.IsTrue(visitor.HasCompleted);

            visitor = new ComparableFindingVisitor<int>(50);
            list.Clear();
            list.AddRange(new[] { 3, 4, 76, 34, 23, 45, 50 });

            list.AcceptVisitor(visitor);
            Assert.IsTrue(visitor.Found);
            Assert.IsTrue(visitor.HasCompleted);

            visitor = new ComparableFindingVisitor<int>(50);
            list.Clear();
            list.AddRange(new[] { 3, 4, 76, 34, 23, 45 });

            list.AcceptVisitor(visitor);
            Assert.IsFalse(visitor.Found);
            Assert.IsFalse(visitor.HasCompleted);
        }
Exemplo n.º 7
0
        public void Customer_data_annotation_test()
        {
            Customer cus = new Customer();
            var context = new ValidationContext(cus, serviceProvider: null, items: null);
            var results = new List<ValidationResult>();
            var isValid = Validator.TryValidateObject(cus, context, results, true);

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

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

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

            Assert.IsEmpty(results);

            results.Clear();

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

            Assert.IsTrue(results.Any(x => x.ErrorMessage == "The Phone Number field is not a valid phone number."));
            Assert.IsTrue(results.Any(x => x.ErrorMessage == "The Email field is not a valid e-mail address."));
        }
Exemplo n.º 8
0
        public void Test_TryGetCommonRootDirectory()
        {
            DirectoryPathAbsolute commonRootDirectory = null;

             // Test when list is null or empty
             Assert.IsFalse(ListOfPathHelper.TryGetCommonRootDirectory(null, out commonRootDirectory));

             List<DirectoryPathAbsolute> list = new List<DirectoryPathAbsolute>();
             Assert.IsFalse(ListOfPathHelper.TryGetCommonRootDirectory(list, out commonRootDirectory));

             // Test when only one dir
             list.Add(new DirectoryPathAbsolute(@"C:\File"));
             Assert.IsTrue(ListOfPathHelper.TryGetCommonRootDirectory(list, out commonRootDirectory));
             Assert.IsTrue(commonRootDirectory.Path == @"C:\File");

             // Test when all dir are the same
             list.Add(new DirectoryPathAbsolute(@"C:\File"));
             list.Add(new DirectoryPathAbsolute(@"C:\File"));
             Assert.IsTrue(ListOfPathHelper.TryGetCommonRootDirectory(list, out commonRootDirectory));
             Assert.IsTrue(commonRootDirectory.Path == @"C:\File");

             // Test when a dir has a wrong drive
             list.Add(new DirectoryPathAbsolute(@"D:\File"));
             Assert.IsFalse(ListOfPathHelper.TryGetCommonRootDirectory(list, out commonRootDirectory));

             // Test when the list contains a null or empty dir
             list.Clear();
             list.Add(new DirectoryPathAbsolute(@"C:\File"));
             list.Add(null);
             Assert.IsFalse(ListOfPathHelper.TryGetCommonRootDirectory(list, out commonRootDirectory));

             list.Clear();
             list.Add(new DirectoryPathAbsolute(@"C:\File"));
             list.Add(DirectoryPathAbsolute.Empty);
             Assert.IsFalse(ListOfPathHelper.TryGetCommonRootDirectory(list, out commonRootDirectory));

             // Test when the common root dir is in the list
             list.Clear();
             list.Add(new DirectoryPathAbsolute(@"C:\File\Debug"));
             list.Add(new DirectoryPathAbsolute(@"C:\File\Debug\Dir1\Dir2"));
             list.Add(new DirectoryPathAbsolute(@"C:\File\Debug\Dir1\Dir2\Dir3"));
             Assert.IsTrue(ListOfPathHelper.TryGetCommonRootDirectory(list, out commonRootDirectory));
             Assert.IsTrue(commonRootDirectory.Path == @"C:\File\Debug");

             list.Add(new DirectoryPathAbsolute(@"C:\File"));
             Assert.IsTrue(ListOfPathHelper.TryGetCommonRootDirectory(list, out commonRootDirectory));
             Assert.IsTrue(commonRootDirectory.Path == @"C:\File");

             list.Add(new DirectoryPathAbsolute(@"C:"));
             Assert.IsTrue(ListOfPathHelper.TryGetCommonRootDirectory(list, out commonRootDirectory));
             Assert.IsTrue(commonRootDirectory.Path == @"C:");

             // Test when the common root dir is not in the list
             list.Clear();
             list.Add(new DirectoryPathAbsolute(@"C:\File\Debug\Dir4"));
             list.Add(new DirectoryPathAbsolute(@"C:\File\Debug\Dir1\Dir2\Dir3"));
             Assert.IsTrue(ListOfPathHelper.TryGetCommonRootDirectory(list, out commonRootDirectory));
             Assert.IsTrue(commonRootDirectory.Path == @"C:\File\Debug");
        }
Exemplo n.º 9
0
        public static void GenerateTestData()
        {
            foreach (var name in _loader.AssetNames)
            {
                var pset = _loader.GetAsset(name).Polygons;

                var lines = new List<string>();
                var indices = new List<int>();

                foreach (WindingRule winding in Enum.GetValues(typeof(WindingRule)))
                {
                    var tess = new Tess();
                    PolyConvert.ToTess(pset, tess);
                    tess.Tessellate(winding, ElementType.Polygons, 3);

                    lines.Add(string.Format("{0} {1}", winding, 3));
                    for (int i = 0; i < tess.ElementCount; i++)
                    {
                        indices.Clear();
                        for (int j = 0; j < 3; j++)
                        {
                            int index = tess.Elements[i * 3 + j];
                            indices.Add(index);
                        }
                        lines.Add(string.Join(" ", indices));
                    }
                    lines.Add("");
                }

                File.WriteAllLines(Path.Combine(TestDataPath, name + ".testdat"), lines);
            }
        }
        public void TestAllPossibleFourOfAKindHands()
        {
            IList<ICard> fourOfAKindCollection = new List<ICard>();
            byte countOfAllValues = 13;
            byte countOfAllKinds = 4;
            Hand playerHand;
            List<bool> results = new List<bool>();
            int faceOfAdditionalCard;

            for (int i = 0; i < countOfAllValues; i++)
            {
                faceOfAdditionalCard = i;

                for (int j = 1; j <= countOfAllKinds; j++)
                {
                    fourOfAKindCollection.Add(new Card((CardFace)i + 2, (CardSuit)j));
                }

                if (faceOfAdditionalCard + 3 > 14)
                {
                    faceOfAdditionalCard = 2;
                }

                fourOfAKindCollection.Add(new Card((CardFace)faceOfAdditionalCard + 3, CardSuit.Hearts));
                playerHand = new Hand(fourOfAKindCollection);

                results.Add(this.checker.IsFourOfAKind(playerHand));

                fourOfAKindCollection.Clear();
            }

            byte countOfAllTrueResults = (byte)results.Count(res => res == true);

            Assert.AreEqual(results.Count, countOfAllTrueResults);
        }
Exemplo n.º 11
0
        public void AssertSequencePattern()
        {
            var dummy = new DummySequencer();
            var goalDistance = 3;
            var lastTrainingDistance = 2;
            var lastRestituteDistance = 0;
            var repeat = 1;
            var e = new SimpleGoaledSequencer<int>(goalDistance, lastTrainingDistance, lastRestituteDistance, repeat, Comparer<int>.Default, dummy);
            var distances = new List<int>();
            while (e.MoveNext())
            {
                var next = e.Current;
                distances.Add(next);
            }

            var expected = "1,2,3";
            var actual = string.Join(",", distances.ConvertAll(x => x.ToString()).ToArray());
            Assert.AreEqual(expected, actual);

            goalDistance = 5;
            repeat = 3;
            lastTrainingDistance = 4;
            expected = "1,2,3,4,4,4,5";
            distances.Clear();
            e = new SimpleGoaledSequencer<int>(goalDistance, lastTrainingDistance, lastRestituteDistance, repeat, Comparer<int>.Default, dummy);
            while (e.MoveNext())
            {
                var next = Convert.ToInt32(e.Current);
                distances.Add(next);
            }
            actual = string.Join(",", distances.ConvertAll(x => x.ToString()).ToArray());
            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 12
0
 public void UserInfo_add_remove_resources() {
     UserInfo userInfo = new UserInfo(1, "wicked");
     int resourcesChanged = 0;
     userInfo.ResourcesChanged += delegate { resourcesChanged++; };
     userInfo.AddResource(1, "0");
     Assert.AreEqual(1, resourcesChanged);
     Assert.AreEqual(1, userInfo.Resources.Length);
     Assert.AreEqual(1, userInfo.Resources[0].Item1);
     userInfo.AddResource(2, "0");
     userInfo.AddResource(3, "0");
     userInfo.AddResource(4, "0");
     Assert.AreEqual(4, resourcesChanged);
     Assert.AreEqual(4, userInfo.Resources.Length);
     List<uint> resources = new List<uint>();
     foreach(Tuplet<uint, string> tuple in userInfo.Resources) {
         resources.Add(tuple.Item1);
     }
     Assert.IsTrue(resources.Contains(2));
     userInfo.RemoveResource(2);
     Assert.AreEqual(5, resourcesChanged);
     Assert.AreEqual(3, userInfo.Resources.Length);
     resources.Clear();
     foreach(Tuplet<uint, string> tuple in userInfo.Resources) {
         resources.Add(tuple.Item1);
     }
     Assert.IsFalse(resources.Contains(2));
 }
Exemplo n.º 13
0
        public void SetUp()
        {
            _scheduler = new ManualTaskScheduler();
            _entries = new List<LogLine>();
            _logFile = new Mock<ILogFile>();
            _logFile.Setup(x => x.GetSection(It.IsAny<LogFileSection>(), It.IsAny<LogLine[]>()))
                    .Callback(
                        (LogFileSection section, LogLine[] entries) =>
                        _entries.CopyTo((int)section.Index, entries, 0, section.Count));
            _logFile.Setup(x => x.AddListener(It.IsAny<ILogFileListener>(), It.IsAny<TimeSpan>(), It.IsAny<int>()))
                    .Callback((ILogFileListener listener, TimeSpan unused, int max) =>
                        {
                            for (int i = 0; i < _entries.Count/max+1; ++i)
                            {
                                int from = i*max;
                                int to = Math.Min((i + 1)*max, _entries.Count);
                                listener.OnLogFileModified(_logFile.Object, new LogFileSection(from, to - from));
                            }
                        });
            _logFile.Setup(x => x.GetLine(It.IsAny<int>())).Returns((int index) => _entries[index]);
            _logFile.Setup(x => x.Count).Returns(() => _entries.Count);
            _logFile.Setup(x => x.EndOfSourceReached).Returns(true);

            _matches = new List<LogMatch>();
            _listener = new Mock<ILogFileSearchListener>();
            _listener.Setup(x => x.OnSearchModified(It.IsAny<ILogFileSearch>(), It.IsAny<List<LogMatch>>()))
                     .Callback((ILogFileSearch sender, IEnumerable<LogMatch> matches) =>
                         {
                             _matches.Clear();
                             _matches.AddRange(matches);
                         });
        }
Exemplo n.º 14
0
        public void TestDuplicateUnbinding()
        {
            Binder binder = new Binder();

            binder.Bind(new SampleEvent1 { Foo = 1 }, new MethodHandler<SampleEvent1>(OnSampleEvent1));
            binder.Bind(new SampleEvent1 { Foo = 2 }, new MethodHandler<SampleEvent1>(OnSpecificSampleEvent1));

            binder.Unbind(new SampleEvent1 { Foo = 1 }, new MethodHandler<SampleEvent1>(OnSampleEvent1));
            binder.Unbind(new SampleEvent1 { Foo = 1 }, new MethodHandler<SampleEvent1>(OnSampleEvent1));

            List<Handler> handlerChain = new List<Handler>();

            handlerChain.Clear();
            Assert.AreEqual(0, binder.BuildHandlerChain(new SampleEvent1 { Foo = 1 }, handlerChain));
            Assert.AreEqual(1, binder.BuildHandlerChain(new SampleEvent1 { Foo = 2 }, handlerChain));
            Assert.AreEqual(new MethodHandler<SampleEvent1>(OnSpecificSampleEvent1), handlerChain[0]);

            // with EventSink

            var sink = new SampleEventSink();
            sink.Bind(new SampleEvent1 { Foo = 1 }, sink.OnSampleEvent1);

            sink.Unbind(new SampleEvent1 { Foo = 1 }, sink.OnSampleEvent1);
            sink.Bind(new SampleEvent1 { Foo = 1 }, sink.OnSampleEvent1);

            handlerChain.Clear();
            Assert.AreEqual(0, binder.BuildHandlerChain(new SampleEvent1 { Foo = 1 }, handlerChain));
            Assert.AreEqual(1, binder.BuildHandlerChain(new SampleEvent1 { Foo = 2 }, handlerChain));
            Assert.AreEqual(new MethodHandler<SampleEvent1>(OnSpecificSampleEvent1), handlerChain[0]);
        }
Exemplo n.º 15
0
        public void Should_allow_multiple_connections()
        {
            var clients = new List<TcpClient>();

            int expected = 100;
            for (int i = 0; i < expected - 1; i++)
            {
                var client = new TcpClient();
                clients.Add(client);

                client.Connect("localhost", 8008);
            }

            Thread.Sleep(50);

            _server.ConnectionCount.ShouldEqual(expected);

            clients.ForEach(client =>
                {
                    using (client)
                        client.Close();
                });

            clients.Clear();
        }
Exemplo n.º 16
0
		public void TestGetActions()
		{
			IPolicySet policySet = ReadPolicySet(m_testPath + "FileTypesAndActions.policy");

			Assert.AreEqual(1, policySet.Policies.Count);
			IPolicy policy = policySet.Policies[0];

			//Check SMTP channel
			List<CellActionsCollection> collections = ExpressionHelpers.GetActions(policy.Channels[0], policySet, false);

			List<Workshare.Policy.ObjectModel.IAction> actions = new List<Workshare.Policy.ObjectModel.IAction>();

			foreach (CellActionsCollection collection in collections)
				actions.AddRange(collection.Actions);

			Assert.AreEqual(2, actions.Count);

			Assert.AreEqual("Alert Action", actions[0].Name.Value);
			Assert.AreEqual("Block Action", actions[1].Name.Value);

			//Check Active Content channel
			collections = ExpressionHelpers.GetActions(policy.Channels[1], policySet, false);
			actions.Clear();

			foreach (CellActionsCollection collection in collections)
				actions.AddRange(collection.Actions);

			Assert.AreEqual(1, actions.Count);

			Assert.AreEqual("Alert Action", actions[0].Name.Value);
		}
        public void TestBasicInOut()
        {
            var one = new object();
            var two = new object();
            var k = "TestBasicInOut";

            this.workPool.RegisterKey(k);
            Assert.IsTrue(this.workPool.AddWorkItem(k, one), "AddWorkItem should return true for new registered keys");
            Assert.IsFalse(this.workPool.AddWorkItem(k, two), "AddWorkItem should return false for existent keys");

            var workList = new List<object>(16);
            var key = this.workPool.NextWorkBlock(ref workList, 1);
            Assert.AreEqual(k, key);
            Assert.AreEqual(1, workList.Count, "Work list length should be 1");
            Assert.AreEqual(one, workList[0]);
            Assert.IsTrue(workPool.FinishWorkBlock(key));

            workList.Clear();
            key = this.workPool.NextWorkBlock(ref workList, 1);
            Assert.AreEqual(k, key);
            Assert.AreEqual(1, workList.Count, "Work list length should be 1");
            Assert.AreEqual(two, workList[0]);

            Assert.IsFalse(workPool.FinishWorkBlock(key));
            Assert.IsNull(workPool.NextWorkBlock(ref workList, 1));
        }
        public void Given_a_stable_live_cell_environment_when_a_moment_passes()
        {
            var cell_death_locations = new List<Location>();
              var cell_birth_locations = new List<Location>();

              var world = World.That_is_a_barren_wasteland();
              world.When_a_cell_dies = location => cell_death_locations.Add(location);
              world.When_a_cell_comes_to_life = location => cell_birth_locations.Add(location);

              world.TouchCellAt(Location.At(0, 0));
              world.TouchCellAt(Location.At(0, 1));
              world.TouchCellAt(Location.At(1, 0));
              world.MomentPassed();

              Assert.That(cell_birth_locations, Is.EquivalentTo(new[] { Location.At(0, 0), Location.At(0, 1), Location.At(1, 0), Location.At(1,1) }), "it should have cause the touched cells to be born.");
              Assert.That(cell_death_locations.ToArray(), Is.Empty, "No cells should have died.");

              cell_death_locations.Clear();
              cell_birth_locations.Clear();

              world.MomentPassed();

              Assert.That(cell_birth_locations, Is.EquivalentTo(Enumerable.Empty<Location>()), "nothing eventful should have happened");
              Assert.That(cell_death_locations.ToArray(), Is.Empty, "nothing eventful should have happened");
        }
Exemplo n.º 19
0
 public void GivenAnEmptyStock()
 {
     _stockTilesList = _domino.GameBoard.BoardTiles;
     _stockTilesList.Clear();
     var stockTilesAmount = _stockTilesList.Count;
     Assert.AreEqual(0, stockTilesAmount);
 }
Exemplo n.º 20
0
        public void Test_GetListOfUniqueDirsAndUniqueFileNames()
        {
            List<FilePathAbsolute> listIn = new List<FilePathAbsolute>();
             List<string> listOfFileNames;
             List<DirectoryPathAbsolute> listOfDirs;

             // Null input
             ListOfPathHelper.GetListOfUniqueDirsAndUniqueFileNames(
            null, out listOfDirs, out listOfFileNames);
             Assert.IsTrue(listOfDirs.Count == 0);
             Assert.IsTrue(listOfFileNames.Count == 0);

             // empty list input
             ListOfPathHelper.GetListOfUniqueDirsAndUniqueFileNames(
            listIn, out listOfDirs, out listOfFileNames);
             Assert.IsTrue(listOfDirs.Count == 0);
             Assert.IsTrue(listOfFileNames.Count == 0);

             // list contains a null ro empty path
             listIn.Add(null);
             ListOfPathHelper.GetListOfUniqueDirsAndUniqueFileNames(
               listIn, out listOfDirs, out listOfFileNames);
             Assert.IsTrue(listOfDirs.Count == 0);
             Assert.IsTrue(listOfFileNames.Count == 0);

             listIn.Clear();
             listIn.Add(FilePathAbsolute.Empty);
             ListOfPathHelper.GetListOfUniqueDirsAndUniqueFileNames(
            listIn, out listOfDirs, out listOfFileNames);
             Assert.IsTrue(listOfDirs.Count == 0);
             Assert.IsTrue(listOfFileNames.Count == 0);

             // Only one path
             listIn.Add(new FilePathAbsolute(@"E:\Path1\Path2\File1.txt"));
             ListOfPathHelper.GetListOfUniqueDirsAndUniqueFileNames(
            listIn, out listOfDirs, out listOfFileNames);
             Assert.IsTrue(listOfDirs.Count == 1);
             Assert.IsTrue(listOfDirs[0].Equals(new DirectoryPathAbsolute(@"E:\Path1\Path2")));
             Assert.IsTrue(listOfFileNames.Count == 1);
             Assert.IsTrue(listOfFileNames[0] == @"File1.txt");

             listIn.Add(new FilePathAbsolute(@"E:\Path1\Path2\File2.txt"));
             ListOfPathHelper.GetListOfUniqueDirsAndUniqueFileNames(
            listIn, out listOfDirs, out listOfFileNames);
             Assert.IsTrue(listOfDirs.Count == 1);
             Assert.IsTrue(listOfDirs[0].Equals(new DirectoryPathAbsolute(@"E:\Path1\Path2")));
             Assert.IsTrue(listOfFileNames.Count == 2);
             Assert.IsTrue(listOfFileNames[0] == @"File1.txt");
             Assert.IsTrue(listOfFileNames[1] == @"File2.txt");

             listIn.Add(new FilePathAbsolute(@"E:\Path3\Path4\file2.txt"));
             ListOfPathHelper.GetListOfUniqueDirsAndUniqueFileNames(
            listIn, out listOfDirs, out listOfFileNames);
             Assert.IsTrue(listOfDirs.Count == 2);
             Assert.IsTrue(listOfDirs[0].Equals(new DirectoryPathAbsolute(@"E:\Path1\Path2")));
             Assert.IsTrue(listOfDirs[1].Equals(new DirectoryPathAbsolute(@"E:\Path3\Path4")));
             Assert.IsTrue(listOfFileNames.Count == 2);
             Assert.IsTrue(listOfFileNames[0] == @"File1.txt");
             Assert.IsTrue(listOfFileNames[1] == @"File2.txt");
        }
        public void CarrierClusterStream_Write_Read_Successfully()
        {
            ICarrierStreamFactory factory = new CarrierStreamFactory();
            factory.RegisterCarrierStreams();

            IList<Stream> streams = new List<Stream>();
            foreach (string fileName in _fileNames)
                streams.Add(File.Open(fileName, FileMode.Open));

            using (Stream carrierClusterStream = factory.BuildClusterStream<CarrierClusterStream>(
                new OneKeySequence(), streams))
            {
                carrierClusterStream.Write(WRITE_READ_VALUE, 0, WRITE_READ_VALUE.Length);
            }

            streams.Clear();
            foreach (string fileName in _fileNames)
                streams.Add(File.Open(fileName, FileMode.Open));

            using (Stream carrierClusterStream = factory.BuildClusterStream<CarrierClusterStream>(
                new OneKeySequence(), streams))
            {
                byte[] readResult = new byte[WRITE_READ_VALUE.Length];

                carrierClusterStream.Seek(0, SeekOrigin.Begin);
                int readLength = carrierClusterStream.Read(readResult, 0, readResult.Length);

                Assert.AreEqual(WRITE_READ_VALUE.Length, readLength);
                Assert.AreEqual(WRITE_READ_VALUE, readResult);
            }
        }
Exemplo n.º 22
0
        public void AddGuidanceItemsToView_and_RemoveGuidanceItemsFromView()
        {
            var createdView = createTempView();
            var viewId = createdView.id.remove("view:").guid();
            var guidanceItemsInView = tmWebServices.GetGuidanceItemsInView(viewId);
            Assert.That(guidanceItemsInView.size()==0, "here guidanceItemsInView should be zero, and it was '{0}'".format(guidanceItemsInView.size()));
            var tempGuidanceItemId_1 = createTempGuidanceItem(createdView.library.guid());
            var tempGuidanceItemId_2 = createTempGuidanceItem(createdView.library.guid());
            var guidanceItemIds = new List<Guid> { tempGuidanceItemId_1,tempGuidanceItemId_2 };
            var result = tmWebServices.AddGuidanceItemsToView(viewId, guidanceItemIds);
            Assert.That(result, "result was false");
            "view ID: {0}".info(viewId);
            guidanceItemsInView = tmWebServices.GetGuidanceItemsInView(viewId);
            Assert.That(guidanceItemsInView.size()==2, "here guidanceItemsInView should be two, and it was '{0}'".format(guidanceItemsInView.size()));

            var tempGuidanceItemId_3 = createTempGuidanceItem(createdView.library.guid());
            var tempGuidanceItemId_4 = createTempGuidanceItem(createdView.library.guid());
            guidanceItemIds.Clear();
            guidanceItemIds.add(tempGuidanceItemId_3).add(tempGuidanceItemId_4);

            result = tmWebServices.AddGuidanceItemsToView(createdView.id.remove("view:").guid(), guidanceItemIds);
            Assert.That(result, "2nd result was false");
            guidanceItemsInView = tmWebServices.GetGuidanceItemsInView(viewId);
            Assert.That(guidanceItemsInView.size()==4, "here guidanceItemsInView should be 4, and it was '{0}'".format(guidanceItemsInView.size()));

            var guidanceIdsToRemove = ( from guidanceItem in guidanceItemsInView
                                        select guidanceItem.Metadata.Id).toList();

            tmWebServices.RemoveGuidanceItemsFromView(viewId, guidanceIdsToRemove);

            guidanceItemsInView = tmWebServices.GetGuidanceItemsInView(viewId);
            Assert.That(guidanceItemsInView.size()==0, "after remove the guidanceItemsInView should be zero, and it was '{0}'".format(guidanceItemsInView.size()));
        }
Exemplo n.º 23
0
        public void CorrectlyRemovesItems()
        {
            const int MaxCount = 20;
            var rand = new Random(Seed);
            var items = new List<PriorityQueueItem<int>>(MaxCount);

            for(int count = 3; count < MaxCount; count++)
            {
                var pq = MakeMaxPQ();
                items.Clear();

                // Prepare
                for (int i = 0; i < count; i++)
                    items.Add(pq.Enqueue(rand.Next()));
                // Invert the comparison to get descending order.
                items.Sort((a, b) => b.Item - a.Item);
                // Remove all the middle elements.
                for (int i = 1; i < count - 1; i++)
                    pq.Remove(items[i].Index);

                // Test
                Assert.That(pq.Dequeue() == items[0].Item, Is.True);
                Assert.That(pq.Dequeue() == items[count - 1].Item, Is.True);
            }
        }
Exemplo n.º 24
0
        public void TestEmptyChildFilter()
        {
            Directory dir = NewDirectory();
            IndexWriterConfig config = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
            config.SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES);
            // we don't want to merge - since we rely on certain segment setup
            IndexWriter w = new IndexWriter(dir, config);

            IList<Document> docs = new List<Document>();

            docs.Add(MakeJob("java", 2007));
            docs.Add(MakeJob("python", 2010));
            docs.Add(MakeResume("Lisa", "United Kingdom"));
            w.AddDocuments(docs);

            docs.Clear();
            docs.Add(MakeJob("ruby", 2005));
            docs.Add(MakeJob("java", 2006));
            docs.Add(MakeResume("Frank", "United States"));
            w.AddDocuments(docs);
            w.Commit();
            int num = AtLeast(10); // produce a segment that doesn't have a value in the docType field
            for (int i = 0; i < num; i++)
            {
                docs.Clear();
                docs.Add(MakeJob("java", 2007));
                w.AddDocuments(docs);
            }

            IndexReader r = DirectoryReader.Open(w, Random().NextBoolean());
            w.Dispose();
            assertTrue(r.Leaves.size() > 1);
            IndexSearcher s = new IndexSearcher(r);
            Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("docType", "resume"))));

            BooleanQuery childQuery = new BooleanQuery();
            childQuery.Add(new BooleanClause(new TermQuery(new Term("skill", "java")), BooleanClause.Occur.MUST));
            childQuery.Add(new BooleanClause(NumericRangeQuery.NewIntRange("year", 2006, 2011, true, true), BooleanClause.Occur.MUST));

            ToParentBlockJoinQuery childJoinQuery = new ToParentBlockJoinQuery(childQuery, parentsFilter, ScoreMode.Avg);

            BooleanQuery fullQuery = new BooleanQuery();
            fullQuery.Add(new BooleanClause(childJoinQuery, BooleanClause.Occur.MUST));
            fullQuery.Add(new BooleanClause(new MatchAllDocsQuery(), BooleanClause.Occur.MUST));
            ToParentBlockJoinCollector c = new ToParentBlockJoinCollector(Sort.RELEVANCE, 1, true, true);
            s.Search(fullQuery, c);
            TopGroups<int> results = c.GetTopGroups(childJoinQuery, null, 0, 10, 0, true);
            assertFalse(float.IsNaN(results.MaxScore));
            assertEquals(1, results.TotalGroupedHitCount);
            assertEquals(1, results.Groups.Length);
            IGroupDocs<int> group = results.Groups[0];
            Document childDoc = s.Doc(group.ScoreDocs[0].Doc);
            assertEquals("java", childDoc.Get("skill"));
            assertNotNull(group.GroupValue);
            Document parentDoc = s.Doc(group.GroupValue);
            assertEquals("Lisa", parentDoc.Get("name"));

            r.Dispose();
            dir.Dispose();
        }
Exemplo n.º 25
0
        public void UseAllConnectionsInPool()
        {
            // As this method uses a lot of connections, clear all connections from all pools before starting.
            // This is needed in order to not reach the max connections allowed and start to raise errors.

            NpgsqlConnection.ClearAllPools();
            try {
                var openedConnections = new List<NpgsqlConnection>();
                // repeat test to exersize pool
                for (var i = 0; i < 10; ++i) {
                    try {
                        // 18 since base class opens two and the default pool size is 20
                        for (var j = 0; j < 18; ++j) {
                            var connection = new NpgsqlConnection(ConnectionString);
                            connection.Open();
                            openedConnections.Add(connection);
                        }
                    } finally {
                        openedConnections.ForEach(delegate(NpgsqlConnection con) { con.Dispose(); });
                        openedConnections.Clear();
                    }
                }
            } finally {
                NpgsqlConnection.ClearAllPools();
            }
        }
Exemplo n.º 26
0
        public void diff_charsToLinesTest()
        {
            var dmp = new diff_match_patchTest();
            // Convert chars up to lines.
            var diffs = new List<Diff>{
                new Diff(Operation.Equal, "\u0001\u0002\u0001"),
                new Diff(Operation.Insert, "\u0002\u0001\u0002")
            };
            var tmpVector = new List<string>{"", "alpha\n", "beta\n"};
            dmp.diff_charsToLines(diffs, tmpVector);
            CollectionAssert.AreEqual(new List<Diff>{
                new Diff(Operation.Equal, "alpha\nbeta\nalpha\n"),
                new Diff(Operation.Insert, "beta\nalpha\nbeta\n")
            }, diffs);

            // More than 256 to reveal any 8-bit limitations.
            const int n = 300;
            tmpVector.Clear();
            var lineList = new StringBuilder();
            var charList = new StringBuilder();
            for (int x = 1; x < n + 1; x++) {
                tmpVector.Add(x + "\n");
                lineList.Append(x + "\n");
                charList.Append(Convert.ToChar(x));
            }
            Assert.AreEqual(n, tmpVector.Count);
            string lines = lineList.ToString();
            string chars = charList.ToString();
            Assert.AreEqual(n, chars.Length);
            tmpVector.Insert(0, "");
            diffs = new List<Diff>{new Diff(Operation.Delete, chars)};
            dmp.diff_charsToLines(diffs, tmpVector);
            CollectionAssert.AreEqual(new List<Diff>
                                      {new Diff(Operation.Delete, lines)}, diffs);
        }
        public void GetLargestGroups()
        {
            var d = new Dictionary<string, int>();

            for (int i = 0; i < _strings.Length; i++)
            {
                int old;
                d.TryGetValue(_strings[i], out old);
                d[_strings[i]] = old + _values[i];
            }

            for (int i = 0; i < _strings.Length; i++)
            {
                Assert.AreEqual(_values[i], d[_strings[i]]);
            }

            var largest = new List<KeyValuePair<string, int>> {new KeyValuePair<string, int>("None", 0)};
            int max = 0;

            // Iterate and find maximum values.
            foreach (var kvp in d)
            {
                if (kvp.Value > max)
                {
                    largest.Clear();
                    max = kvp.Value;
                }
                if (kvp.Value == max)
                    largest.Add(kvp);
            }

            Assert.AreEqual(2, largest.Count);
            Assert.IsTrue(largest.Contains(new KeyValuePair<string, int>("b", 42)));
            Assert.IsTrue(largest.Contains(new KeyValuePair<string, int>("d", 42)));
        }
        public static TestCaseConfig Read(TextReader reader)
        {
            var line = reader.ReadLine().Trim();
            Assert.AreEqual("/*---", line);
            var lines = new List<string>();
            string rawLine;
            while((line = (rawLine = reader.ReadLine()).Trim()) != "---" && line != "*/")
                lines.Add(rawLine);

            var vson = string.Join("\r\n", lines);
            var config = JsonConvert.DeserializeObject<TestCaseConfig>(vson);

            if(line == "---")
            {
                // read in expected console output
                lines.Clear();
                while((line = (rawLine = reader.ReadLine()).Trim()) != "*/")
                    lines.Add(rawLine);

                config.VerifyConsoleOutput = true;
                config.ExpectedConsoleOutput = string.Join("\r\n", lines);
            }

            return config;
        }
Exemplo n.º 29
0
		public void SearchTest()
		{
			DynamicRTree<int> rTree = new DynamicRTree<int>(new GuttmanQuadraticInsert<int>(),
			                                                new GuttmanQuadraticSplit<int>(), new DynamicRTreeBalanceHeuristic());

			addEntries(rTree);

			List<RTreeIndexEntry<int>> resultsList = new List<RTreeIndexEntry<int>>();

			resultsList.AddRange(rTree.Search(new BoundingBox(-100, -100, 5928.57523425, 3252.50803582)));
			Assert.AreEqual(8, resultsList.Count);
			resultsList.Clear();

			resultsList.AddRange(rTree.Search(new BoundingBox(0, 0, 100, 100)));
			Assert.AreEqual(6, resultsList.Count);
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 1; }));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 2; }));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 3; }));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 6; }));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 7; }));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 8; }));
			resultsList.Clear();

			resultsList.AddRange(rTree.Search(new BoundingBox(1500, 1500, 1500, 1500)));
			Assert.AreEqual(2, resultsList.Count);
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 4; }));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 5; }));
			resultsList.Clear();

			resultsList.AddRange(rTree.Search(new BoundingBox(100, 100, 100, 100)));
			Assert.AreEqual(4, resultsList.Count);
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 1; }));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 2; }));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 7; }));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 8; }));
			resultsList.Clear();

			addRandomEntries(rTree);
			resultsList.AddRange(rTree.Search(new BoundingBox(100, 100, 100, 100)));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 1; }));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 2; }));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 7; }));
			Assert.IsTrue(resultsList.Exists(delegate(RTreeIndexEntry<int> match) { return match.Value == 8; }));
			resultsList.Clear();

			rTree.Dispose();
		}
Exemplo n.º 30
0
 public void TestCount()
 {
     List<object> list = new List<object>(new object[] { "a", "b" });
     var test = new CollectionAdapter<object, string>(list);
     Assert.True(test.Count == 2);
     list.Clear();
     Assert.True(test.Count == 0);
 }