public void AccountForEfficiencies_FixedEnd_MultipleDateIntervalEfficiencies_ReturnsCorrectAnswer()
        {
            //         +------------+
            //       |0|  |0|  |0|

            // Result:
            //   +------------------+
            //       |0|  |0|  |0|

            // Arrange
            var now = DateTime.Now;
            var dateInterval = new DateInterval(now, now.AddDays(5));

            var dateIntervalEfficiencies = new List<DateIntervalEfficiency>();
            var efficiency1 = new DateIntervalEfficiency(now.AddDays(1), now.AddDays(2), 0);
            var efficiency2 = new DateIntervalEfficiency(now.AddDays(3), now.AddDays(4), 0);
            var efficiency3 = new DateIntervalEfficiency(now.AddDays(5), now.AddDays(6), 0);

            dateIntervalEfficiencies.Add(efficiency1);
            dateIntervalEfficiencies.Add(efficiency2);
            dateIntervalEfficiencies.Add(efficiency3);

            // Act
            var newDateInterval = dateInterval.AccountForEfficiencies(dateIntervalEfficiencies, FixedEndPoint.Max);

            var correctDateInterval = new DateInterval(dateInterval.Max.Value.Add(-dateInterval.Duration).Add(-efficiency1.Duration).Add(-efficiency2.Duration).Add(-efficiency3.Duration), dateInterval.Max.Value);

            // Assert
            Assert.AreEqual(correctDateInterval, newDateInterval);
        }
        public void ShouldGetCustomNumbers(int value)
        {
            var result = sut.CustomNumbers(value);
            List<string> numbers = new List<string>();
            for (int i = 1; i <= value; i++)
            {
                if (((i % 5) == 0 && (i % 3) == 0)) //Multiple of 5 and  3
                {
                    numbers.Add("Z");
                }
                else if ((i % 5) == 0) //Multiple of 5
                {
                    numbers.Add("E");
                }
                else if ((i % 3) == 0)//Multiple OF 3
                {
                    numbers.Add("C");
                }
                else
                {
                    numbers.Add(i.ToString());
                }

            }

            Assert.That(result, Is.EqualTo(numbers));
        }
            public void WithSelf()
            {
                var source = new WithSelf();
                var propertyChanges = new List<string>();
                var changes = new List<EventArgs>();
                var expectedChanges = new List<EventArgs>();

                using (var tracker = Track.Changes(source, ReferenceHandling.Structural))
                {
                    tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName);
                    tracker.Changed += (_, e) => changes.Add(e);
                    Assert.AreEqual(0, tracker.Changes);
                    CollectionAssert.IsEmpty(propertyChanges);
                    CollectionAssert.IsEmpty(changes);

                    source.Value = source;
                    Assert.AreEqual(1, tracker.Changes);
                    CollectionAssert.AreEqual(new[] { "Changes" }, propertyChanges);
                    expectedChanges.Add(RootChangeEventArgs.Create(ChangeTrackerNode.GetOrCreate(source, tracker.Settings, false).Value, new PropertyChangeEventArgs(source, source.GetProperty(nameof(source.Value)))));
                    CollectionAssert.AreEqual(expectedChanges, changes, EventArgsComparer.Default);

                    source.Name += "abc";
                    Assert.AreEqual(2, tracker.Changes);
                    CollectionAssert.AreEqual(new[] { "Changes", "Changes" }, propertyChanges);
                    expectedChanges.Add(RootChangeEventArgs.Create(ChangeTrackerNode.GetOrCreate(source, tracker.Settings, false).Value, new PropertyChangeEventArgs(source, source.GetProperty(nameof(source.Name)))));
                    CollectionAssert.AreEqual(expectedChanges, changes, EventArgsComparer.Default);
                }
            }
        public void Test_Add_ListAll()
        {
            List<Orderline> orderlines = new List<Orderline>();
            Orderline OL1 = new Orderline() { OrderId = 2, MovieId = 6, Amount = 6, Price = 30 };
            Orderline Ol2 = new Orderline() { OrderId = 2, MovieId = 17, Amount = 8, Price = 30 };
            orderlines.Add(Ol2);
            orderlines.Add(OL1);
            CustomerRepository custrepo = new CustomerRepository();

            Customer cust = custrepo.Get(3);
            Status stat = new Status() { Id = 1, Name = "Shipped" };
            Order ord = new Order() { Id = 2, Orderlines = orderlines, Customer = cust, OrderDate = DateTime.Now.Date, Status = stat };

            ord.Id = 2;
            ord.Orderlines = orderlines;
            ord.Customer = cust;
            ord.OrderDate = DateTime.Now.Date;
            ord.Status = stat;

            OrderRepository ordrepo= new OrderRepository();
            int numberOfOrders = ordrepo.GetAll().Count();

            Order result1 = ordrepo.Add(ord);
            Assert.NotNull(result1);

            Order result2 = ordrepo.Get(result1.Id);
            Assert.NotNull(result2);
            Assert.AreEqual(result1.Id, result2.Id);

            int finalNumberOfOrders = ordrepo.GetAll().Count();
            Assert.AreEqual(numberOfOrders + 1, finalNumberOfOrders);
        }
        public void Equals()
        {
            string program = TestUtil.TypeMemberParse("public string Sentence(string title , string text);");
            CompilationUnit cu = TestUtil.ParseProgram(program);

            NamespaceDeclaration ns = (NamespaceDeclaration) cu.Children[0];
            TypeDeclaration ty = (TypeDeclaration) ns.Children[0];
            MethodDeclaration pgMethod = (MethodDeclaration) ty.Children[0];
            ParameterDeclarationExpression p1 = new ParameterDeclarationExpression(new TypeReference("string"), "title");
            p1.TypeReference.RankSpecifier = new int[] {};
            ParameterDeclarationExpression p2 = new ParameterDeclarationExpression(new TypeReference("string"), "text");
            p2.TypeReference.RankSpecifier = new int[] {};
            List<ParameterDeclarationExpression> argList = new List<ParameterDeclarationExpression>();
            argList.Add(p1);
            argList.Add(p2);
            MethodDeclaration exMethod = new MethodDeclaration("Sentence",
                                                               Modifiers.Public,
                                                               new TypeReference("string"),
                                                               argList, null);

            Assert.IsTrue(Equals(exMethod, pgMethod));

            string program2 = TestUtil.TypeMemberParse("public string Sentence(string title , string[] text);");
            cu = TestUtil.ParseProgram(program2);

            ns = (NamespaceDeclaration) cu.Children[0];
            ty = (TypeDeclaration) ns.Children[0];
            pgMethod = (MethodDeclaration) ty.Children[0];
            Assert.IsFalse(Equals(exMethod, pgMethod));
        }
        public void CreatesASingleProjectWhenOnlyBranches()
        {
            var mockTranslator = new Mock<ISQKeyTranslator>();
            var mockRest = new Mock<ISonarRestService>();
            var mockLogger = new Mock<INotificationManager>();
            var mockConfiguration = new Mock<IConfigurationHelper>();
            var mockPlugin = new Mock<IPluginManager>();
            var mockSourceProvider = new Mock<ISourceControlProvider>();
            var mockVsHelper = new Mock<IVsEnvironmentHelper>();

            mockConfiguration.Setup(x => x.ReadSetting(It.IsAny<Context>(), It.IsAny<string>(), It.IsAny<string>())).Returns(new SonarQubeProperties() { Value = "dummy" });
            var mockObj = mockConfiguration.Object;

            var brancheData = new List<Resource>();
            brancheData.Add(new Resource() { Key = "tekla.utilities:project:master", Name = "project master", BranchName = "master", IsBranch = true });
            brancheData.Add(new Resource() { Key = "tekla.utilities:project:feature_A", Name = "project feature_A", BranchName = "feature_A", IsBranch = true });
            brancheData.Add(new Resource() { Key = "tekla.utilities:project:feature_B", Name = "project feature_B", BranchName = "feature_B", IsBranch = true });

            mockRest.Setup(x => x.GetProjectsList(It.IsAny<ISonarConfiguration>())).Returns(brancheData);
            var associationModel = new SonarQubeViewModel("test", mockConfiguration.Object, mockLogger.Object, mockTranslator.Object, mockRest.Object, locaAnalyser: mockAnalyser.Object);
            associationModel.RefreshProjectList(false);
            Assert.That(associationModel.AvailableProjects.Count, Is.EqualTo(1));
            Assert.That(associationModel.AvailableProjects[0].BranchResources.Count, Is.EqualTo(3));
            Assert.That(associationModel.AvailableProjects[0].Name, Is.EqualTo("project"));
            Assert.That(associationModel.AvailableProjects[0].BranchResources[0].BranchName, Is.EqualTo("master"));
            Assert.That(associationModel.AvailableProjects[0].BranchResources[1].BranchName, Is.EqualTo("feature_A"));
            Assert.That(associationModel.AvailableProjects[0].BranchResources[2].BranchName, Is.EqualTo("feature_B"));
        }
        // PHASE 1 - TASKS
    	        
        public void task1_copyAssessmentFiles(IAnalysisArtifacts analysisArtifacts)
        {        
            if (deletePhase1FolderBeforeCopying)
                Files.deleteAllFilesFromDir(folderWithArtifacts_Phase1);
                
            var filesCopied = new List<string>();
            foreach(var fileOrFolder in analysisArtifacts.assessmentFilesOrFolderToLoad)
            {        		
                if (File.Exists(fileOrFolder))
                    filesCopied.Add(Files.CopyVerbose(fileOrFolder, folderWithArtifacts_Phase1,dontCopyIfTargetFileAlreadyExists));
                else 
                    if (Directory.Exists(fileOrFolder))        		        			
                        foreach(var assessmentFile in Files.getFilesFromDir_returnFullPath(fileOrFolder, "*.ozasmt", true))
                            filesCopied.Add(Files.CopyVerbose(assessmentFile, folderWithArtifacts_Phase1,dontCopyIfTargetFileAlreadyExists));
            }

  			            
            //check to see if files were copied  ok
            foreach(var file in  filesCopied)
            {
                var fileName = Path.GetFileName(file);
                var targetFolder = folderWithArtifacts_Phase1;
                var expectedFile = Path.Combine(targetFolder, fileName);
                Assert.That(File.Exists(expectedFile),"Expected file did not exist " + expectedFile);
            }
        }
        public void CanBeUsedByLinqSetOperatorsSuchAsIntersect()
        {
            IList<ConcreteEntityWithDomainSignatureProperties> objects1 =
                new List<ConcreteEntityWithDomainSignatureProperties>();
            var object1 = new ConcreteEntityWithDomainSignatureProperties { Name = "Billy McCafferty", };
            EntityIdSetter.SetIdOf(object1, 2);
            objects1.Add(object1);

            IList<ConcreteEntityWithDomainSignatureProperties> objects2 =
                new List<ConcreteEntityWithDomainSignatureProperties>();
            var object2 = new ConcreteEntityWithDomainSignatureProperties { Name = "Jimi Hendrix", };
            EntityIdSetter.SetIdOf(object2, 1);
            objects2.Add(object2);
            var object3 = new ConcreteEntityWithDomainSignatureProperties
                {
                    Name =
                        "Doesn't Matter since the Id will match and the presedence of the domain signature will go overridden", 
                };
            EntityIdSetter.SetIdOf(object3, 2);
            objects2.Add(object3);

            Assert.That(
                objects1.Intersect(
                    objects2, new BaseObjectEqualityComparer<ConcreteEntityWithDomainSignatureProperties>()).Count(), 
                Is.EqualTo(1));
            Assert.AreEqual(
                objects1.Intersect(
                    objects2, new BaseObjectEqualityComparer<ConcreteEntityWithDomainSignatureProperties>()).First(), 
                object1);
            Assert.AreEqual(
                objects1.Intersect(
                    objects2, new BaseObjectEqualityComparer<ConcreteEntityWithDomainSignatureProperties>()).First(), 
                object3);
        }
Beispiel #9
0
        public void Run(string[] args, string sourceFile, string targetFile, bool checkOutput)
        {
            // console programs' Main are static, so lock concurrent access to
            // a test code. we use a private field to lock upon

            lock (locked)
            {
                List<string> completeArgs = new List<string>(args.Length + 2);

                for (int i = 0; i < args.Length; ++i)
                    completeArgs.Add(args[i]);

                completeArgs.Add(sourceFile);
                completeArgs.Add(targetFile);

                File.Delete(targetFile);

                BitMiracle.TiffCP.Program.Main(completeArgs.ToArray());

                string sampleFile = targetFile.Replace(@"\Output.Tiff\", @"\Expected.Tiff\");
                Assert.IsTrue(File.Exists(targetFile));

                if (checkOutput)
                    FileAssert.AreEqual(sampleFile, targetFile);
            }
        }
Beispiel #10
0
 protected override void GetLibrariesToPreload(List<string> libraries)
 {
     libraries.Add("VMDataBridge.dll");
     libraries.Add("DSCoreNodes.dll");
     libraries.Add("DSIronPython.dll");
     base.GetLibrariesToPreload(libraries);
 }
Beispiel #11
0
        public void TestExploit()
        {
            List<string> files = new List<string>();

            files.Add(@"C:\Dev\hMailServer\exploit\CREATE.txt");
            files.Add(@"C:\Dev\hMailServer\exploit\APPEND.txt");
            files.Add(@"C:\Dev\hMailServer\exploit\EXAMINE.txt");
            files.Add(@"C:\Dev\hMailServer\exploit\LIST1.txt");
            files.Add(@"C:\Dev\hMailServer\exploit\LIST2.txt");
            files.Add(@"C:\Dev\hMailServer\exploit\LSUB.txt");
            files.Add(@"C:\Dev\hMailServer\exploit\RENAME1.txt");
            files.Add(@"C:\Dev\hMailServer\exploit\RENAME2.txt");
            files.Add(@"C:\Dev\hMailServer\exploit\SEARCH.txt");
            files.Add(@"C:\Dev\hMailServer\exploit\SELECT.txt");
            files.Add(@"C:\Dev\hMailServer\exploit\STATUS.txt");
            files.Add(@"C:\Dev\hMailServer\exploit\SUBSCRIBE.txt");
            files.Add(@"C:\Dev\hMailServer\exploit\UNSUBSCRIBE.txt");

            foreach (string file in files)
            {
                SendExploitFile(file, false);
            }

            foreach (string file in files)
            {
                SendExploitFile(file, true);
            }
        }
        public void AvailabilityValueWritesAvailabilityProperty()
        {
            JulianDate start = new JulianDate(new GregorianDate(2012, 4, 2, 1, 2, 3));
            JulianDate stop = new JulianDate(new GregorianDate(2012, 4, 3, 1, 2, 3));

            m_output.WriteStartSequence();
            using (PacketCesiumWriter packet = m_writer.OpenPacket(m_output))
            {
                packet.WriteAvailability(start, stop);
            }
            using (PacketCesiumWriter packet = m_writer.OpenPacket(m_output))
            {
                packet.WriteAvailability(new TimeInterval(start, stop));
            }
            using (PacketCesiumWriter packet = m_writer.OpenPacket(m_output))
            {
                var intervals = new List<TimeInterval>();
                intervals.Add(new TimeInterval(start, stop));
                intervals.Add(new TimeInterval(start.AddDays(2.0), stop.AddDays(2.0)));
                packet.WriteAvailability(intervals);
            }
            m_output.WriteEndSequence();

            Assert.AreEqual("[{\"availability\":\"20120402T010203Z/20120403T010203Z\"}," +
                            "{\"availability\":\"20120402T010203Z/20120403T010203Z\"}," +
                            "{\"availability\":[\"20120402T010203Z/20120403T010203Z\",\"20120404T010203Z/20120405T010203Z\"]}]",
                            m_sw.ToString());
        }
		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");
		}
Beispiel #14
0
        public void CreatePassportProjectToFileWithToTest()
        {
            var pathFileSave = Path.Combine(Path.GetTempPath(), "UPPY" + Environment.TickCount + ".tmp");
            var list = new List<HierarchyNumberDrawing>();
            list.Add(new HierarchyNumberDrawing() { HierarchyNumber = "1.", TechRouteId = 2 });
            list.Add(new HierarchyNumberDrawing() { HierarchyNumber = "1.1.", TechRouteId = 4 });
            list.Add(new HierarchyNumberDrawing() { HierarchyNumber = "2.", });// TechRouteId = 1
            list.Add(new HierarchyNumberDrawing() { HierarchyNumber = "3.", TechRouteId = 3 });
            list.Add(new HierarchyNumberDrawing() { HierarchyNumber = "4.", TechRouteId = 5 });

            var listTo = new List<TechOperation>();
            listTo.Add(new TechOperation() { Id = 1, ShortName = "A" });
            listTo.Add(new TechOperation() { Id = 2, ShortName = "B" });
            listTo.Add(new TechOperation() { Id = 3, ShortName = "C" });
            listTo.Add(new TechOperation() { Id = 4, ShortName = "D" });
            listTo.Add(new TechOperation() { Id = 5, ShortName = "E" });

            var listTr = new List<TechRoute>();
            listTr.Add(new TechRoute() { Id = 1, TechOperations = new List<TechOperation>() { new TechOperation() { Id = 1 }, new TechOperation() { Id = 2 } } });
            listTr.Add(new TechRoute() { Id = 2, TechOperations = new List<TechOperation>() { new TechOperation() { Id = 2 }, new TechOperation() { Id = 3 } } });
            listTr.Add(new TechRoute() { Id = 3, TechOperations = new List<TechOperation>() { new TechOperation() { Id = 3 }, new TechOperation() { Id = 5 } } });
            listTr.Add(new TechRoute() { Id = 4, TechOperations = new List<TechOperation>() { new TechOperation() { Id = 1 }, new TechOperation() { Id = 2 }, new TechOperation() { Id = 4 } } });
            listTr.Add(new TechRoute() { Id = 5, TechOperations = new List<TechOperation>() { new TechOperation() { Id = 5 } } });

            var header = new Order();

            ExportExcelFile excelFile = new ExportExcelFile();

            Debug.WriteLine(pathFileSave);

            Assert.DoesNotThrow(() =>
            {
                excelFile.CreatePassportProjectToFile(header, list, listTo, listTr, pathFileSave);
            });
        }
		public void Test()
		{
			var CustomThreadPool = new CustomThreadPool(2);
			var Results0 = new List<int>();
			var Results1 = new List<int>();
			var CountdownEvent = new CountdownEvent(2);

			CustomThreadPool.AddTask(0, () =>
			{
				Thread.Sleep(10);
				Results0.Add(0);
			});
			CustomThreadPool.AddTask(0, () =>
			{
				Results0.Add(1);
				CountdownEvent.Signal();
			});
			CustomThreadPool.AddTask(1, () =>
			{
				Results1.Add(0);
				CountdownEvent.Signal();
			});

			CountdownEvent.Wait();
			Thread.Sleep(10);
			Assert.IsTrue(CustomThreadPool.GetLoopIterCount(0) <= 2);
			Assert.IsTrue(CustomThreadPool.GetLoopIterCount(1) <= 2);
			Assert.AreEqual("0,1", Results0.ToStringArray());
			Assert.AreEqual("0", Results1.ToStringArray());
			CustomThreadPool.Stop();
		}
        public int GetsCorrectVictor(Pick p1, Pick p2)
        {
            List<IPlayer> players = new List<IPlayer>();
            IPlayer player1 = Substitute.For<IPlayer>();
            player1.Pick.Returns(p1);
            player1.Slot.Returns(1);
            players.Add(player1);
            IPlayer player2 = Substitute.For<IPlayer>();
            player2.Pick.Returns(p2);
            player2.Slot.Returns(2);

            players.Add(player2);

            var game = new Game(players);

            var gameResult = Result.None;
            var victor = -1;

            game.GameEnds = (result, i) =>
            {
                gameResult = result;
                victor = i;
            };

            game.StartGame();
            Thread.Sleep(100);
            Assert.AreEqual(Result.Victory, gameResult);

            return victor;
        }
Beispiel #17
0
        public void GetTable_Returns_Correct_Table()
        {
            var projectList = new List<ProjectDescriptor>();
            var project = new ProjectDescriptor();
            const string projectName = "abcdef";
            project.Name = projectName;
            const string path = "c:\\dac.dacpac";
            project.DacPath = path;

            projectList.Add(project);

            var enumerator = new Mock<ProjectEnumerator>();
            enumerator.Setup(p => p.EnumerateProjects()).Returns(projectList);

            var tables = new List<ITable>();
            tables.Add(new Table() { SchemaName = "one", Name = "table" });
            tables.Add(new Table() { SchemaName = "one", Name = "table2" });
            tables.Add(new Table() { SchemaName = "two", Name = "table" });

            var parser = new Mock<DacParser>();
            parser.Setup(p => p.PreDeployScript).Returns(() => null);
            parser.Setup(p => p.PostDeployScript).Returns(() => null);
            parser.Setup(p => p.GetTableDefinitions()).Returns(tables);

            var parserBuilder = new Mock<DacParserBuilder>();
            parserBuilder.Setup(p => p.Build(path)).Returns(parser.Object);

            var solution = new SolutionParser(enumerator.Object, parserBuilder.Object, new DummyStatus());

            var table = solution.GetTable("abcdef", "one", "table2");
            Assert.AreEqual("one", table.SchemaName);
            Assert.AreEqual("table2", table.Name);
        }
        public void TodasAsPessoasVotaramEmTodasAsPizzasO_RankingEhProcessado()
        {
            var pessoa1 = new Pessoa();
            var pessoa2 = new Pessoa();
            var pessoasNaReuniao = new List<Pessoa> { pessoa1, pessoa2 };

            var pizza1 = new Pizza();

            var pizza2 = new Pizza();

            var pizzasRankeadasEsperado = new List<Pizza>();
            pizzasRankeadasEsperado.Add(pizza2);
            pizzasRankeadasEsperado.Add(pizza1);

            var opcoesPizzas = new List<Pizza> { pizza1, pizza2 };
            var pizzasRankeadas = new List<Pizza>();

            PedindoPizza pedindoPizza = new PedindoPizza(pessoasNaReuniao, opcoesPizzas);
            pedindoPizza.Avaliar(pessoa1, pizza1, 1);
            pedindoPizza.Avaliar(pessoa1, pizza2, 5);
            pedindoPizza.Avaliar(pessoa2, pizza1, 5);
            pedindoPizza.Avaliar(pessoa2, pizza2, 3);

            pizzasRankeadas = pedindoPizza.ProcessarRanking();

            Assert.AreEqual(pizzasRankeadasEsperado, pizzasRankeadas);
        }
		private IQueryable<User> MockedGetAll()
		{
			List<User> users = new List<User>();
			users.Add(new User(Guid.NewGuid(), "komil.patel", "*****@*****.**", "Komil", "Patel", false, true));
			users.Add(new User(Guid.NewGuid(), "nikki.patel", "*****@*****.**", "Nikki", "Patel", false, true));
			return users.AsQueryable();
		}
        public void TestCase2()
        {
            // test case 2 data setup
            // wallet 1 credit cards
            List<string> creditCardList1 = new List<string>();
            creditCardList1.Add("Visa");
            creditCardList1.Add("Discover");

            // wallet 2 credit cards
            List<string> creditCardList2 = new List<string>();
            creditCardList2.Add("MasterCard");

            Person personB = new Person();
            Wallet wallet1 = new Wallet(creditCardList1);
            personB.addWallet(wallet1);

            Assert.AreEqual(11, wallet1.getTotalInterest());

            Wallet wallet2 = new Wallet(creditCardList2);
            personB.addWallet(wallet2);

            Assert.AreEqual(5, wallet2.getTotalInterest());

            Assert.AreEqual(16, personB.getTotalInterestPerPerson());
        }
Beispiel #21
0
        public void Astronomy_HasOneSunsets_Should_ReturnCorrectSunset()
        {
            // Arrange
            var astro = new Astronomy ();
            var events = new List<AstronomyEvent> ();

            var sunrise = new AstronomyEvent
            {
                Type = AstronomyEventType.Rise,
                Time = new DateTime().AddHours (1).AddMinutes(58)
            };

            var sunset = new AstronomyEvent
            {
                Type = AstronomyEventType.Set,
                Time = new DateTime().AddHours (0).AddMinutes(3)
            };

            events.Add (sunrise);
            events.Add (sunset);

            astro.Events = events;

            // Act
            var set = astro.Sunset;

            // Assert
            Assert.AreEqual (sunset.Time.Hour, set.Value.Hour);
            Assert.AreEqual (sunset.Time.Minute, set.Value.Minute);
        }
        public void TestCase3()
        {
            // test case 3 data setup
            // wallet 3 credit cards
            List<string> creditCardList3 = new List<string>();
            creditCardList3.Add("MasterCard");
            creditCardList3.Add("Visa");

            // wallet 4 credit cards
            List<string> creditCardList4 = new List<string>();
            creditCardList4.Add("Visa");
            creditCardList4.Add("MasterCard");

            Person personC = new Person();
            Wallet wallet3 = new Wallet(creditCardList3);
            personC.addWallet(wallet3);

            Assert.AreEqual(15, personC.getTotalInterestPerPerson());

            Person personD = new Person();
            Wallet wallet4 = new Wallet(creditCardList4);
            personD.addWallet(wallet4);

            Assert.AreEqual(15, personD.getTotalInterestPerPerson());
        }
Beispiel #23
0
        public virtual void TestFilteredDocIdSet()
        {
            const int maxdoc = 10;
            DocIdSet innerSet = new DocIdSetAnonymousInnerClassHelper(this, maxdoc);

            DocIdSet filteredSet = new FilteredDocIdSetAnonymousInnerClassHelper(this, innerSet);

            DocIdSetIterator iter = filteredSet.GetIterator();
            List<int?> list = new List<int?>();
            int doc = iter.Advance(3);
            if (doc != DocIdSetIterator.NO_MORE_DOCS)
            {
                list.Add(Convert.ToInt32(doc));
                while ((doc = iter.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS)
                {
                    list.Add(Convert.ToInt32(doc));
                }
            }

            int[] docs = new int[list.Count];
            int c = 0;
            IEnumerator<int?> intIter = list.GetEnumerator();
            while (intIter.MoveNext())
            {
                docs[c++] = (int)intIter.Current;
            }
            int[] answer = new int[] { 4, 6, 8 };
            bool same = Arrays.Equals(answer, docs);
            if (!same)
            {
                Console.WriteLine("answer: " + Arrays.ToString(answer));
                Console.WriteLine("gotten: " + Arrays.ToString(docs));
                Assert.Fail();
            }
        }
        public void CorrelationSequenceIsIncremented()
        {
            var correlationSequenceNumbers = new List<int>();
            var counter = new SharedCounter(1);

            _activator1.Handle<string>(async (bus, ctx, str) =>
            {
                correlationSequenceNumbers.Add(int.Parse(ctx.Headers[Headers.CorrelationSequence]));
                await bus.Advanced.Routing.Send("bus2", "hej!");
            });
            _activator2.Handle<string>(async (bus, ctx, str) =>
            {
                correlationSequenceNumbers.Add(int.Parse(ctx.Headers[Headers.CorrelationSequence]));
                await bus.Advanced.Routing.Send("bus3", "hej!");
            });
            _activator3.Handle<string>(async (bus, ctx, str) =>
            {
                correlationSequenceNumbers.Add(int.Parse(ctx.Headers[Headers.CorrelationSequence]));
                counter.Decrement();
            });

            _activator1.Bus.SendLocal("heeeej!").Wait();

            counter.WaitForResetEvent();

            Assert.That(correlationSequenceNumbers, Is.EqualTo(new[] { 0, 1, 2 }));
        }
        public void ArrayLiterals()
        {
            var array = new[] { 42 };
            Assert.AreEqual (typeof(int[]), array.GetType (), "You don't have to specify a type if the elements can be inferred");
            Assert.AreEqual (new int[] { 42 }, array, "These arrays are literally equal... But you won't see this string in the error message.");

            //Are arrays 0-based or 1-based?
            Assert.AreEqual (42, array [0], "Well, it's either 0 or 1.. you have a 110010-110010 chance of getting it right.");

            //This is important because...
            Assert.IsTrue (array.IsFixedSize, "...because Fixed Size arrays are not dynamic");

            //Begin RJG
            // Moved this Throws() call to a separate FixedSizeArraysCannotGrow() method below
            //...it means we can't do this: array[1] = 13;
            //Assert.Throws(typeof(FILL_ME_IN), delegate() { array[1] = 13; });
            //End RJG

            //This is because the array is fixed at length 1. You could write a function
            //which created a new array bigger than the last, copied the elements over, and
            //returned the new array. Or you could do this:
            var dynamicArray = new List<int> ();
            dynamicArray.Add (42);
            CollectionAssert.AreEqual (array, dynamicArray.ToArray (), "Dynamic arrays can grow");

            dynamicArray.Add (13);
            CollectionAssert.AreEqual ((new int[] { 42, (int)13 }), dynamicArray.ToArray (), "Identify all of the elements in the array");
        }
        public void CorrelationIdFlows()
        {
            var correlationIds = new List<string>();
            var counter = new SharedCounter(1);

            _activator1.Handle<string>(async (bus, ctx, str) =>
            {
                correlationIds.Add(ctx.Headers[Headers.CorrelationId]);
                await bus.Advanced.Routing.Send("bus2", "hej!");
            });
            _activator2.Handle<string>(async (bus, ctx, str) =>
            {
                correlationIds.Add(ctx.Headers[Headers.CorrelationId]);
                await bus.Advanced.Routing.Send("bus3", "hej!");
            });
            _activator3.Handle<string>(async (bus, ctx, str) =>
            {
                correlationIds.Add(ctx.Headers[Headers.CorrelationId]);
                counter.Decrement();
            });

            _activator1.Bus.SendLocal("heeeej!").Wait();

            counter.WaitForResetEvent();

            Assert.That(correlationIds.GroupBy(c => c).Count(), Is.EqualTo(1));
        }
Beispiel #27
0
 protected override void GetLibrariesToPreload(List<string> libraries)
 {
     libraries.Add("ProtoGeometry.dll");
     libraries.Add("DSCoreNodes.dll");
     libraries.Add("FunctionObject.ds");
     base.GetLibrariesToPreload(libraries);
 }
        public void SimulateConnectedCBNExecution()
        {
            // Simulate 2 CBNs where one is connected to the other
            // [a = 1]----->[x = a]
            List<string> codes = new List<string>() 
            {
                @"a = 10;", // CBN 1 contents
                @"x = a;"   // CBN 2 contents
            };

            // Simulate 2 CBNs
            Guid cbnGuid1 = System.Guid.NewGuid(); 
            Guid cbnGuid2 = System.Guid.NewGuid(); 
            List<Subtree> added = new List<Subtree>();
            added.Add(ProtoTestFx.TD.TestFrameWork.CreateSubTreeFromCode(cbnGuid1, codes[0]));
            added.Add(ProtoTestFx.TD.TestFrameWork.CreateSubTreeFromCode(cbnGuid2, codes[1]));
            var syncData = new GraphSyncData(null, added, null);

            // Sending the CBN node data to the VM
            // Execute the DS code
            liveRunner.UpdateGraph(syncData);

            // Verify the values of the variables in the CBNs
            AssertValue("a", 10);
            AssertValue("x", 10);
        }
Beispiel #29
0
        public void WriteLog()
        {
            aosLogger.getInstance().LogFilePath =             
                "../../Test_Data/aosHelperTests/log.txt";

            // Очистка лог файла
            aosLogger.getInstance().ClearLog();

            // Сообщения
            List<string> msgList = new List<string>();
            msgList.Add("02.06.2014:12.12.12 Error!");
            msgList.Add("02.07.2015:12.16.18 No errors!");

            // Запись сообщений в лог
            foreach (string msg in msgList)
                aosLogger.getInstance().WriteLog(msg);

            // Утверждения
            using (StreamReader reader =
                new StreamReader("../../Test_Data/aosHelperTests/log.txt"))
            {
                int i = 0;
                while (!reader.EndOfStream)
                {
                    Assert.AreEqual(msgList[i], reader.ReadLine());
                    ++i;
                }
            }
        }
        public void _01_GetAttributeValueTest()
        {
            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);
                
                // Open RW session
                using (Session session = slot.OpenSession(false))
                {
                    // Login as normal user
                    session.Login(CKU.CKU_USER, Settings.NormalUserPin);
                    
                    // Create object
                    ObjectHandle objectHandle = Helpers.CreateDataObject(session);

                    // Prepare list of empty attributes we want to read
                    List<CKA> attributes = new List<CKA>();
                    attributes.Add(CKA.CKA_LABEL);
                    attributes.Add(CKA.CKA_VALUE);

                    // Get value of specified attributes
                    List<ObjectAttribute> objectAttributes = session.GetAttributeValue(objectHandle, attributes);

                    // Do something interesting with attribute value
                    Assert.IsTrue(objectAttributes[0].GetValueAsString() == Settings.ApplicationName);

                    session.DestroyObject(objectHandle);
                    session.Logout();
                }
            }
        }