public void Setup()
        {
            m_StartSegment = Substitute.For <ITurnCircleArcSegment>();
            m_MiddleSegment = Substitute.For <ITurnCircleArcSegment>();
            m_EndSegment = Substitute.For <ITurnCircleArcSegment>();

            m_Path = Substitute.For <IPath>();
            var segments = new List <IPolylineSegment>
                           {
                               m_StartSegment,
                               m_MiddleSegment,
                               m_EndSegment
                           };

            m_Path.Segments.Returns(segments);

            m_ArcSegmentOne = new ArcSegment(new Point(10.0,
                                                       10.0),
                                             new Size(10.0,
                                                      10.0),
                                             45.0,
                                             false,
                                             SweepDirection.Clockwise,
                                             false);

            m_LineSegment = new LineSegment(new Point(20.0,
                                                      20.0),
                                            false);

            m_ArcSegmentTwo = new ArcSegment(new Point(30.0,
                                                       30.0),
                                             new Size(30.0,
                                                      30.0),
                                             90.0,
                                             false,
                                             SweepDirection.Counterclockwise,
                                             false);

            m_ArcSegmentThree = new ArcSegment(new Point(40.0,
                                                         40.0),
                                               new Size(40.0,
                                                        40.0),
                                               135.0,
                                               false,
                                               SweepDirection.Counterclockwise,
                                               false);


            m_Point = new Point(10.0,
                                10.0);

            m_Helper = Substitute.For <IPathSegmentHelper>();
            m_Helper.SegmentToLineSegment(Line.Unknown).ReturnsForAnyArgs(m_LineSegment);
            m_Helper.SegmentToArcSegment(TurnCircleArcSegment.Unknown).ReturnsForAnyArgs(m_ArcSegmentOne,
                                                                                         m_ArcSegmentTwo,
                                                                                         m_ArcSegmentThree);
            m_Helper.PointRelativeToOrigin(null).ReturnsForAnyArgs(m_Point);

            m_Converter = new RacetrackPathUTurnToFiguresConverter(m_Helper);
        }
Esempio n. 2
9
        protected override async Task LoadContent()
        {
            await base.LoadContent();

            wireframeState = new RasterizerStateDescription(CullMode.Back) { FillMode = FillMode.Wireframe };

            simpleEffect = new EffectInstance(new Effect(GraphicsDevice, SpriteEffect.Bytecode));

            // TODO GRAPHICS REFACTOR
            simpleEffect.Parameters.Set(TexturingKeys.Texture0, UVTexture);
            simpleEffect.UpdateEffect(GraphicsDevice);

            primitives = new List<GeometricPrimitive>();

            // Creates all primitives
            primitives = new List<GeometricPrimitive>
                             {
                                 GeometricPrimitive.Plane.New(GraphicsDevice),
                                 GeometricPrimitive.Cube.New(GraphicsDevice),
                                 GeometricPrimitive.Sphere.New(GraphicsDevice),
                                 GeometricPrimitive.GeoSphere.New(GraphicsDevice),
                                 GeometricPrimitive.Cylinder.New(GraphicsDevice),
                                 GeometricPrimitive.Torus.New(GraphicsDevice),
                                 GeometricPrimitive.Teapot.New(GraphicsDevice),
                                 GeometricPrimitive.Capsule.New(GraphicsDevice, 0.5f, 0.3f),
                                 GeometricPrimitive.Cone.New(GraphicsDevice)
                             };


            view = Matrix.LookAtRH(new Vector3(0, 0, 5), new Vector3(0, 0, 0), Vector3.UnitY);

            Window.AllowUserResizing = true;
        }
 public void AssertImportTwoDifferentRecordsResults(List<CdrTaRecord> details, 
     CdrRtdRecord record1, CdrRtdRecord record2)
 {
     AssertResultsWithTwoDetails(details, record1, record2);
     AssertDistributionParameters(details[0], record1);
     AssertDistributionParameters(details[1], record2);
 }
Esempio n. 4
8
        public void test1()
        {
            UndirectedGraph<int, Edge<int>> graph = new UndirectedGraph<int, Edge<int>>(true);

            // Add vertices to the graph
            graph.AddVertex(0);
            graph.AddVertex(1);
            graph.AddVertex(2);
            graph.AddVertex(3);
            // Create the edges
            Edge<int> e0_1 = new Edge<int>(0, 1);
            Edge<int> e0_2 = new Edge<int>(0, 2);
            Edge<int> e1_2 = new Edge<int>(1, 2);
            Edge<int> e1_3 = new Edge<int>(1, 3);
            // Add the edges
            graph.AddEdge(e0_1);
            graph.AddEdge(e0_2);
            graph.AddEdge(e1_2);
            graph.AddEdge(e1_3);

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

            HamiltonianDefiner definer = new HamiltonianDefiner(graph);
            bool isHamiltonian = definer.isHamiltonianGraph(path);
            Assert.AreEqual(isHamiltonian, false);
        }
Esempio n. 5
8
        public void GivenXdocumentWhenReadThenDlvAndPtnsAreMapped()
        {
            _memStream = new MemoryStream();
            using (var xmlWriter = XmlWriter.Create(_memStream, new XmlWriterSettings { Encoding = new UTF8Encoding(false) }))
            {
                xmlWriter.WriteStartElement("TIM");
                xmlWriter.WriteStartElement("PTN");
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("DLV");
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("DLV");
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("DLV");
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();
                xmlWriter.Flush();
                xmlWriter.Close();
            }

            var xpathDoc = CreateXDoc();

            var ptn = new PTN();
            _ptnReaderMock.Setup(x => x.Read(It.IsAny<XPathNodeIterator>())).Returns(new List<PTN> { ptn });

            var dlvs = new List<DLV> { new DLV(), new DLV(), new DLV() };
            _dlvReaderMock.Setup(x => x.Read(It.Is<XPathNodeIterator>(y => y.Count == 3))).Returns(dlvs);

            var result = _timReader.Read(xpathDoc).First();
            Assert.AreSame(ptn, result.Items[0]);
            Assert.AreSame(dlvs[0], result.Items[1]);
            Assert.AreSame(dlvs[1], result.Items[2]);
            Assert.AreSame(dlvs[2], result.Items[3]);
        }
Esempio n. 6
6
        public void VirtualIds()
        {
            const int BOX1ID = 22;
            const int BOX2ID = 23;
            const int ATTEMPTS = 1000;
            // store ids
            List<long> b1 = new List<long>(ATTEMPTS);
            List<long> b2 = new List<long>(ATTEMPTS);
            // create a new tracker with virtual id represent my book
            it = new IdTracker(BOX1ID);
            // create a second tracker with unique id
            IdTracker it2 = new IdTracker(BOX2ID);
            // make sure consequetive assignments don't match
            Assert.AreNotEqual(it.AssignId, it.AssignId);
            // make sure checks of ids do match
            Assert.AreEqual(it.NextId, it.NextId);
            // assign 1000 ids to make sure we overlap with tracker2 initial id
            for (int i = 0; i < ATTEMPTS; i++)
            {
                b1.Add(it.AssignId);
            }
            // assign 1000 ids to make sure we overlap with tracker1 assignments
            for (int i = 0; i < ATTEMPTS; i++)
            {
                b2.Add(it2.AssignId);
            }
            bool overlap = false;
            // test for id overlap
            for (int i = 0; i < ATTEMPTS; i++)
                for (int j = 0; j < ATTEMPTS; j++)
                    overlap |= (b1[i] == b2[j]);
            Assert.IsFalse(overlap, "ids overlapped");

        }
 public void GenerateFullManifest()
 {
     ManifestGenerator generator = new ManifestGenerator();
     IntegrationRequest request = new IntegrationRequest(BuildCondition.ForceBuild, "Somewhere", null);
     IntegrationSummary summary = new IntegrationSummary(IntegrationStatus.Success, "A Label", "Another Label", new DateTime(2009, 1, 1));
     IntegrationResult result = new IntegrationResult("Test project", "Working directory", "Artifact directory", request, summary);
     Modification modification1 = GenerateModification("first file", "Add");
     Modification modification2 = GenerateModification("second file", "Modify");
     result.Modifications = new Modification[] { modification1, modification2 };
     List<string> files = new List<string>();
     files.Add("first file");
     XmlDocument manifest = generator.Generate(result, files.ToArray());
     Assert.IsNotNull(manifest);
     string actualManifest = manifest.OuterXml;
     string expectedManifest = "<manifest>"  +
             "<header project=\"Test project\" label=\"A Label\" build=\"ForceBuild\" status=\"Unknown\">" +
                 "<modification user=\"johnDoe\" changeNumber=\"1\" time=\"2009-01-01T00:00:00\">" +
                     "<comment>A comment</comment>" +
                     "<file name=\"first file\" type=\"Add\" />" +
                     "<file name=\"second file\" type=\"Modify\" />" +
                 "</modification>" +
             "</header>" +
             "<file name=\"first file\" />" +
         "</manifest>";
     Assert.AreEqual(expectedManifest, actualManifest);
 }
        public void GetAllCategories_Test()
        {
            var service = Create<BlogEngineService>();

            IList<Category> list = new List<Category>();
            for (int i = 0; i < 5; i++)
            {
                list.Add(Mock<Category>());
            }

            using (Record)
            {
                var categoryRepository = Get<ICategoryRepository>();
                Expect.Call(categoryRepository.RetrieveAll()).Return(list);
            }

            using (Playback)
            {
                Category[] result = service.GetAllCategories();
                Category[] expected = list.ToArray();

                Assert.IsNotNull(result);
                CollectionAssert.AllItemsAreNotNull(result);
                CollectionAssert.AreEqual(result, expected);
            }
        }
Esempio n. 9
1
        static void TestRollingEventSequence(
            IEnumerable<LogEvent> events,
            int? retainedFiles,
            Action<IList<string>> verifyWritten)
        {
            var fileName = Some.String() + "-{Date}.txt";
            var folder = Some.TempFolderPath();
            var pathFormat = Path.Combine(folder, fileName);

            var log = new LoggerConfiguration()
                .WriteTo.RollingFile(pathFormat, retainedFileCountLimit: retainedFiles)
                .CreateLogger();

            var verified = new List<string>();

            try
            {
                foreach (var @event in events)
                {
                    Clock.SetTestDateTimeNow(@event.Timestamp.DateTime);
                    log.Write(@event);

                    var expected = pathFormat.Replace("{Date}", @event.Timestamp.ToString("yyyyMMdd"));
                    Assert.That(File.Exists(expected));

                    verified.Add(expected);
                }
            }
            finally
            {
                ((IDisposable)log).Dispose();
                verifyWritten(verified);
                Directory.Delete(folder, true);
            }
        }
        public void SetPlayers_ShouldAddPlayers()
        {
            var players = new List<string>() { "Horse", "Car"};

            gameBuilder.SetPlayers(players);
            Assert.That(gameBuilder.GetGame().Players, Is.EquivalentTo(players));
        }
Esempio n. 11
1
        public void Add()
        {
            var criteria = new List<IIterationStopCriterium>
                           {
                               new FailureStopCriterium(),
                               new DivergenceStopCriterium(),
                               new IterationCountStopCriterium(),
                               new ResidualStopCriterium()
                           };
            var iterator = new Iterator();
            Assert.AreEqual(0, iterator.NumberOfCriteria, "Incorrect criterium count");

            foreach (var criterium in criteria)
            {
                iterator.Add(criterium);
                Assert.IsTrue(iterator.Contains(criterium), "Missing criterium");
            }

            // Check that we have all the criteria
            Assert.AreEqual(criteria.Count, iterator.NumberOfCriteria, "Incorrect criterium count");
            var enumerator = iterator.StoredStopCriteria;
            while (enumerator.MoveNext())
            {
                var criterium = enumerator.Current;
                Assert.IsTrue(criteria.Exists(c => ReferenceEquals(c, criterium)), "Criterium missing");
            }
        }
        public void TestConcurrentQueueDeclare()
        {
            string x = GenerateExchangeName();
            Random rnd = new Random();

            List<Thread> ts = new List<Thread>();
            System.NotSupportedException nse = null;
            for(int i = 0; i < 256; i++)
            {
                Thread t = new Thread(() =>
                        {
                            try
                            {
                                // sleep for a random amount of time to increase the chances
                                // of thread interleaving. MK.
                                Thread.Sleep(rnd.Next(5, 500));
                                Model.ExchangeDeclare(x, "fanout", false, false, null);
                            } catch (System.NotSupportedException e)
                            {
                                nse = e;
                            }
                        });
                ts.Add(t);
                t.Start();
            }

            foreach (Thread t in ts)
            {
                t.Join();
            }

            Assert.IsNotNull(nse);
            Model.ExchangeDelete(x);
        }
 protected void AssertResultsWithTwoDetails(List<CdrTaRecord> details, CdrRtdRecord record1,
     CdrRtdRecord record2)
 {
     Assert.AreEqual(details.Count, 2);
     AssertBasicParameters(details[0], record1);
     AssertBasicParameters(details[1], record2);
 }
            public void CreateAndDisposeParentChildLoop()
            {
                var parent = new Parent { Child = new Child("c") };
                parent.Child.Parent = parent;
                Assert.AreSame(parent, parent.Child.Parent);
                Assert.AreSame(parent.Child, parent.Child.Parent.Child);
                var propertyChanges = new List<string>();
                var changes = new List<EventArgs>();
                var tracker = Track.Changes(parent, 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);

                tracker.Dispose();
                Assert.AreEqual(0, tracker.Changes);
                CollectionAssert.IsEmpty(propertyChanges);
                CollectionAssert.IsEmpty(changes);

                parent.Name += "abc";
                Assert.AreEqual(0, tracker.Changes);
                CollectionAssert.IsEmpty(propertyChanges);
                CollectionAssert.IsEmpty(changes);

                parent.Child.Name += "abc";
                Assert.AreEqual(0, tracker.Changes);
                CollectionAssert.IsEmpty(propertyChanges);
                CollectionAssert.IsEmpty(changes);
            }
        public void SetUp()
        {
            _store = NewDocumentStore();
            _store.Initialize();

            // We first have to create the static indexes
            IndexCreation.CreateIndexes(typeof(Player_Index_R03).Assembly, _store);

            _teams = DataGenerator.CreateTeamList();

            // Store some players and teams in the database
            using (var session = _store.OpenSession())
            {
                foreach (var team in _teams)
                {
                    session.Store(team);
                }

                _players = DataGenerator.CreatePlayerListWithTeamIds();

                foreach (var player in _players)
                {
                    session.Store(player);
                }

                session.SaveChanges();
            }

            // Let's wait for indexing to happen
            // this method is part of RavenTestBase and thus should only be used in tests
            WaitForIndexing(_store);
        }
Esempio n. 16
0
        public void PostingInterests_NoPosting()
        {
            //            Assert.Ignore();
            SavingsBookProduct product = new SavingsBookProduct
            {
                Id = 1,
                InterestBase = OSavingInterestBase.Daily,
                InterestFrequency = OSavingInterestFrequency.EndOfYear,
                Periodicity = new InstallmentType("Yearly", 0, 12)

            };
            SavingBookContract saving = new SavingBookContract(
                                                        ApplicationSettings.GetInstance(""),
                                                        new User(),
                                                        new DateTime(2009, 01, 01),
                                                        null)
                                            {
                                                Product = product,
                                                InterestRate = 0.1,
                                                NextMaturity = new DateTime(2009, 01, 01)
                                            };
            List<SavingInterestsPostingEvent> list = new List<SavingInterestsPostingEvent>();
            list = saving.PostingInterests(new DateTime(2009, 02, 01), new User { Id = 1 });

            Assert.AreEqual(list.Count, 0);
        }
        public void Setup()
        {
            _series = Builder<Series>
                    .CreateNew()
                    .Build();

            _episode = Builder<Episode>
                    .CreateNew()
                    .With(e => e.SeriesId = _series.SeriesId)
                    .With(e => e.Series = _series)
                    .Build();

            _episodes = Builder<Episode>
                    .CreateListOfSize(10)
                    .All()
                    .With(e => e.SeriesId = _series.SeriesId)
                    .With(e => e.Series = _series)
                    .Build()
                    .ToList();

            _parseResults = Builder<EpisodeParseResult>
                    .CreateListOfSize(10)
                    .Build();

            _indexer1 = new Mock<IndexerBase>();
            _indexer2 = new Mock<IndexerBase>();
            _indexers = new List<IndexerBase> { _indexer1.Object, _indexer2.Object };

            Mocker.GetMock<IndexerProvider>()
                  .Setup(c => c.GetEnabledIndexers())
                  .Returns(_indexers);
        }
        public static void TestOptimizer( int[] coordinates, int[] expectedCoordinates, IShapeOptimizer optimizer )
        {
            List<IntPoint> shape = new List<IntPoint>( );
            List<IntPoint> expectedShape = new List<IntPoint>( );

            // build a shape top optimize
            for ( int i = 0, n = coordinates.Length / 2; i < n; i++ )
            {
                shape.Add( new IntPoint( coordinates[i * 2], coordinates[i * 2 + 1] ) );
            }

            // build a shape, which should be result of optimization
            for ( int i = 0, n = expectedCoordinates.Length / 2; i < n; i++ )
            {
                expectedShape.Add( new IntPoint( expectedCoordinates[i * 2], expectedCoordinates[i * 2 + 1] ) );
            }

            List<IntPoint> optimizedShape = optimizer.OptimizeShape( shape );

            // check number of points in result shape
            Assert.AreEqual( expectedShape.Count, optimizedShape.Count );

            // check that all points matches with expected
            for ( int i = 0, n = optimizedShape.Count; i < n; i++ )
            {
                Assert.AreEqual( expectedShape[i], optimizedShape[i] );
            }
        }
Esempio n. 19
0
        public void AllSimpleTests()
        {
            var defaultProvider = MakeDefaultProvider();
            var simpleTests = Directory.GetFiles(
                Path.GetFullPath(Path.Combine(ComparisonTest.TestSourceFolder, "SimpleTestCases")),
                "*.cs"
            );
            var failureList = new List<string>();

            foreach (var filename in simpleTests) {
                Console.Write("// {0} ... ", Path.GetFileName(filename));

                try {
                    // We reuse the same type info provider for all the tests in this folder so they run faster
                    using (var test = new ComparisonTest(filename, null, defaultProvider))
                        test.Run();
                } catch (Exception ex) {
                    failureList.Add(Path.GetFileNameWithoutExtension(filename));
                    if (ex.Message == "JS test failed")
                        Debug.WriteLine(ex.InnerException);
                    else
                        Debug.WriteLine(ex);
                }
            }

            Assert.AreEqual(0, failureList.Count,
                String.Format("{0} test(s) failed:\r\n{1}", failureList.Count, String.Join("\r\n", failureList.ToArray()))
            );
        }
 private void CreateRandomIndexes(int maxSegments)
 {
     dir = NewDirectory();
     numDocs = AtLeast(150);
     int numTerms = TestUtil.NextInt(Random(), 1, numDocs / 5);
     ISet<string> randomTerms = new HashSet<string>();
     while (randomTerms.size() < numTerms)
     {
         randomTerms.add(TestUtil.RandomSimpleString(Random()));
     }
     terms = new List<string>(randomTerms);
     int seed = Random().Next();
     IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(new Random(seed)));
     iwc.SetMergePolicy(TestSortingMergePolicy.NewSortingMergePolicy(sort));
     iw = new RandomIndexWriter(new Random(seed), dir, iwc);
     for (int i = 0; i < numDocs; ++i)
     {
         Document doc = RandomDocument();
         iw.AddDocument(doc);
         if (i == numDocs / 2 || (i != numDocs - 1 && Random().nextInt(8) == 0))
         {
             iw.Commit();
         }
         if (Random().nextInt(15) == 0)
         {
             string term = RandomInts.RandomFrom(Random(), terms);
             iw.DeleteDocuments(new Term("s", term));
         }
     }
     reader = iw.Reader;
 }
        public void Should_Return_Highest_AccessLevel_Based_On_Role()
        {
            RunActionInTransaction(session =>
                {
                    var accessRules = new List<AccessRule>(new[] {
                                                new AccessRule { Identity = "RoleA", AccessLevel = AccessLevel.Deny, IsForRole = true},
                                                new AccessRule { Identity = "Admin", AccessLevel = AccessLevel.ReadWrite, IsForRole = true},
                                                new AccessRule { Identity = "RoleB", AccessLevel = AccessLevel.Read, IsForRole = true}
                                             });

                    var page = TestDataProvider.CreateNewPage();
                    accessRules.ForEach(page.AddRule);

                    session.SaveOrUpdate(page);
                    session.Flush();
                    session.Clear();

                    var service = CreateAccessControlService();

                    var principal = new GenericPrincipal(new GenericIdentity("John"), new[] { "Admin" });
                    var accessLevel = service.GetAccessLevel(page, principal);

                    Assert.AreEqual(AccessLevel.ReadWrite, accessLevel);
                });
        }
Esempio n. 22
0
        public void TestRoundTrip_Assign02()
        {
            //=================================
            // 1. Build AST 
            // 2. Execute AST and verify
            // 3. Convert AST to source
            // 4. Execute source and verify
            //=================================

            int result1 = 30;
            ExecutionMirror mirror = null;

            // 1. Build the AST tree
            ProtoCore.AST.AssociativeAST.BinaryExpressionNode assign = new ProtoCore.AST.AssociativeAST.BinaryExpressionNode(
                new ProtoCore.AST.AssociativeAST.IdentifierNode("a"),
                new ProtoCore.AST.AssociativeAST.BinaryExpressionNode(
                    new ProtoCore.AST.AssociativeAST.IntNode(10),
                    new ProtoCore.AST.AssociativeAST.IntNode(20),
                    ProtoCore.DSASM.Operator.add),
                ProtoCore.DSASM.Operator.assign);
            List<ProtoCore.AST.AssociativeAST.AssociativeNode> astList = new List<ProtoCore.AST.AssociativeAST.AssociativeNode>();
            astList.Add(assign);

            // 2. Execute AST and verify
            mirror = thisTest.RunASTSource(astList);
            Assert.IsTrue((Int64)mirror.GetValue("a").Payload == result1);

            // 3. Convert AST to source
            ProtoCore.CodeGenDS codegenDS = new ProtoCore.CodeGenDS(astList);
            string code = codegenDS.GenerateCode();

            // 4. Execute source and verify
            mirror = thisTest.RunScriptSource(code);
            Assert.IsTrue((Int64)mirror.GetValue("a").Payload == result1);
        }
        public void Setup()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var resource = "All.com.robobat.UnitTests.TxtFiles.JSONBreakingBadShow.txt";
            using (Stream stream = assembly.GetManifestResourceStream(resource))
            using (StreamReader reader = new StreamReader(stream))
            {
                _FULLSHOWJSON = reader.ReadToEnd();
            }

            JSONParserForTMDB myParser = new JSONParserForTMDB(_FULLSHOWJSON);

            _FULLJSONSEASONLIST = new List<string>();

            for (int i = 1; i <= 5; i++)
            {
                resource = "All.com.robobat.UnitTests.TxtFiles.JSONBreakingBadSeason" + i + ".txt";
                using (Stream stream = assembly.GetManifestResourceStream(resource))
                using (StreamReader reader = new StreamReader(stream))
                {
                    _FULLJSONSEASONLIST.Add(reader.ReadToEnd());
                }
            }

            myParser.PopulateSeasonsFromJsonList(_FULLJSONSEASONLIST);
            _myShow = myParser.show;
        }
        public void IndexDecider_EndsUpInTheOutput()
        {
            //DO NOTE that you cant send objects as scalar values through Logger.*("{Scalar}", {});
            var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
            const string messageTemplate = "{Song}++ @{Complex}";
            var template = new MessageTemplateParser().Parse(messageTemplate);
            _options.IndexDecider = (l, utcTime) => string.Format("logstash-{1}-{0:yyyy.MM.dd}", utcTime, l.Level.ToString().ToLowerInvariant());
            using (var sink = new ElasticsearchSink(_options))
            {
                var properties = new List<LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) };
                var e = new LogEvent(timestamp, LogEventLevel.Information, null, template, properties);
                sink.Emit(e);
                var exception = new ArgumentException("parameter");
                properties = new List<LogEventProperty>
                {
                    new LogEventProperty("Song", new ScalarValue("Old Macabre")),
                    new LogEventProperty("Complex", new ScalarValue(new { A  = 1, B = 2}))
                };
                e = new LogEvent(timestamp.AddYears(-2), LogEventLevel.Fatal, exception, template, properties);
                sink.Emit(e);
            }

            _seenHttpPosts.Should().NotBeEmpty().And.HaveCount(1);
            var json = _seenHttpPosts.First();
            var bulkJsonPieces = json.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            bulkJsonPieces.Should().HaveCount(4);
            bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-information-2013.05.28");
            bulkJsonPieces[1].Should().Contain("New Macabre");
            bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-fatal-2011.05.28");
            bulkJsonPieces[3].Should().Contain("Old Macabre");

            //serilog by default simpy .ToString()'s unknown objects
            bulkJsonPieces[3].Should().Contain("Complex\":\"{");

        }
        /// <summary>
        /// Set up correct handling of the InformClientOfNeighbour call from the source region that triggers the
        /// viewer to setup a connection with the destination region.
        /// </summary>
        /// <param name='tc'></param>
        /// <param name='neighbourTcs'>
        /// A list that will be populated with any TestClients set up in response to 
        /// being informed about a destination region.
        /// </param>
        public static void SetupInformClientOfNeighbourTriggersNeighbourClientCreate(
            TestClient tc, List<TestClient> neighbourTcs)
        {
            // XXX: Confusingly, this is also used for non-neighbour notification (as in teleports that do not use the
            // event queue).

            tc.OnTestClientInformClientOfNeighbour += (neighbourHandle, neighbourExternalEndPoint) =>
            {
                uint x, y;
                Utils.LongToUInts(neighbourHandle, out x, out y);
                x /= Constants.RegionSize;
                y /= Constants.RegionSize;

                m_log.DebugFormat(
                    "[TEST CLIENT]: Processing inform client of neighbour located at {0},{1} at {2}", 
                    x, y, neighbourExternalEndPoint);

                AgentCircuitData newAgent = tc.RequestClientInfo();

                Scene neighbourScene;
                SceneManager.Instance.TryGetScene(x, y, out neighbourScene);

                TestClient neighbourTc = new TestClient(newAgent, neighbourScene);
                neighbourTcs.Add(neighbourTc);
                neighbourScene.AddNewAgent(neighbourTc, PresenceType.User);
            };
        }
Esempio n. 26
0
		public void TestIncomingMessageQueue()
		{
			var processed = new List<MessageSet>();
			var testQueue = new IncomingMessageQueue(processed.Add);

			var testSets = new[]
			{
				new MessageSet {Number = 2},
				new MessageSet {Number = 1},
				new MessageSet {Number = 3},
				new MessageSet {Number = 4},
				new MessageSet {Number = 5},
				new MessageSet {Number = 7},
				new MessageSet {Number = 8},
				new MessageSet {Number = 6},
				new MessageSet {Number = 9},
				new MessageSet {Number = 10}
			};

			foreach (var messageSet in testSets)
				testQueue.ProcessMessageSet(messageSet);

			Assert.AreEqual(processed.Count, 10);

			int numberTest = 1;
			foreach (var eventSet in processed)
				Assert.AreEqual(eventSet.Number, numberTest++);

			Assert.AreEqual(testQueue.NextMessageSetNumber, 11);
		}
        public void When_GetViewModel_Then_hazardous_substances_are_put_in_view_model_and_prepends_please_select_empty_option()
        {
            // Given
            var returnedHazardousSubstances = new List<HazardousSubstanceDto>()
                                              {
                                                  new HazardousSubstanceDto() { Id = 1, Name = "hazsub 01"},
                                                  new HazardousSubstanceDto() { Id = 2, Name = "hazsub 02" },
                                                  new HazardousSubstanceDto() { Id = 3, Name = "hazsub 03" },
                                                  new HazardousSubstanceDto() { Id = 4, Name = "hazsub 04" }
                                              };
            _hazardousSubstanceService
                .Setup(x => x.Search(It.IsAny<SearchHazardousSubstancesRequest>()))
                .Returns(returnedHazardousSubstances);

            // When
            var result = _target.WithCompanyId(1234).GetViewModel();

            // Then
            Assert.That(result.HazardousSubstances.Count(), Is.EqualTo(5));
            Assert.That(result.HazardousSubstances.First().value, Is.EqualTo(string.Empty));
            Assert.That(result.HazardousSubstances.First().label, Is.EqualTo("--Select Option--"));
            for (var i = 1; i < returnedHazardousSubstances.Count; i++)
            {
                Assert.That(result.HazardousSubstances.Skip(i).Take(1).First().label, Is.EqualTo(returnedHazardousSubstances.ElementAt(i - 1).Name));
                Assert.That(result.HazardousSubstances.Skip(i).Take(1).First().value, Is.EqualTo(returnedHazardousSubstances.ElementAt(i - 1).Id.ToString()));
            }
        }
            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);
                }
            }
Esempio n. 29
-1
        public void TestAddedNodes02()
        {
            List<string> codes = new List<string>() 
            {
                "a = 1; b = a;"
            };

            Guid guid = System.Guid.NewGuid();
            List<Subtree> added = new List<Subtree>();
            added.Add(CreateSubTreeFromCode(guid, codes[0]));

            var syncData = new GraphSyncData(null, added, null);

            // Get astlist from ChangeSetComputer
            ChangeSetComputer changeSetState = new ProtoScript.Runners.ChangeSetComputer(core);
            List<AssociativeNode> astList = changeSetState.GetDeltaASTList(syncData);

            // Get expected ASTList
            // The list must be in the order that it is expected
            List<string> expectedCode = new List<string>() 
            {
                "a = 1;",
                "b = a;"
            };
            List<AssociativeNode> expectedAstList = ProtoCore.Utils.CoreUtils.BuildASTList(core, expectedCode);

            // Compare ASTs to be equal
            for (int n = 0; n < astList.Count; ++n)
            {
                AssociativeNode node1 = astList[n];
                AssociativeNode node2 = expectedAstList[n];
                bool isEqual = node1.Equals(node2);
                Assert.IsTrue(isEqual);
            }
        }
        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();
                }
            }
        }