Пример #1
0
        static void Main(string[] args)
        {
            var test = new TestUtils();

            // Initialize the console
            var sourceObj = new object();
            ConsoleManager.Instance.InitializeProcessor(new JintConsoleProcessor());
            ConsoleManager.Instance.RegisterObjectToConsole(sourceObj, "test", test);
            ConsoleLib.Helpers.Formatters.RegisterJsonObjectFormatter(sourceObj);

            dynamic expandoTest = new ExpandoObject();;
            expandoTest.abc = "def";
            ConsoleManager.Instance.RegisterObjectToConsole(sourceObj, "expandoTest", expandoTest);

            var host = new ConsoleServiceHost("localhost", 4000);

            Console.WriteLine("Server started, waiting for commands");

            while (!test.Quit)
            {
                // Keep looping until quit has been called
                Thread.Sleep(100);
            }

            ConsoleManager.Instance.UnregisterObjectsFromSource(sourceObj);
        }
Пример #2
0
        public void TestQueryEntityConfiguration()
        {
            var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
            {
                BinaryConfiguration = new BinaryConfiguration(typeof(QueryPerson)),
                CacheConfiguration  = new[]
                {
                    new CacheConfiguration(CacheName, new QueryEntity(typeof(int), typeof(QueryPerson))
                    {
                        TableName = "CustomTableName",
                        Fields    = new[]
                        {
                            new QueryField("Name", typeof(string)),
                            new QueryField("Age", typeof(int)),
                            new QueryField("Birthday", typeof(DateTime)),
                        },
                        Indexes = new[]
                        {
                            new QueryIndex
                            {
                                InlineSize = 2048,
                                IndexType  = QueryIndexType.FullText,
                                Fields     = new[]
                                {
                                    new QueryIndexField
                                    {
                                        IsDescending = false,
                                        Name         = "Name"
                                    }
                                }
                            },
                            new QueryIndex("Age")
                        }
                    })
                }
            };

            using (var ignite = Ignition.Start(cfg))
            {
                var cache = ignite.GetCache <int, QueryPerson>(CacheName);

                Assert.IsNotNull(cache);

                cache[1] = new QueryPerson("Arnold", 10);
                cache[2] = new QueryPerson("John", 20);

                using (var cursor = cache.Query(new SqlQuery(typeof(QueryPerson), "age > ? and birthday < ?",
                                                             10, DateTime.UtcNow)))
                {
                    Assert.AreEqual(2, cursor.GetAll().Single().Key);
                }

                using (var cursor = cache.Query(new SqlFieldsQuery(
                                                    "select _key from CustomTableName where age > ? and birthday < ?", 10, DateTime.UtcNow)))
                {
                    Assert.AreEqual(2, cursor.GetAll().Single()[0]);
                }

                using (var cursor = cache.Query(new TextQuery(typeof(QueryPerson), "Ar*")))
                {
                    Assert.AreEqual(1, cursor.GetAll().Single().Key);
                }
            }
        }
Пример #3
0
        public void TestSerializeAndDeserializeRecoveryMessageWithChangeViewsAndPrepareRequest()
        {
            Transaction[] txs = new Transaction[5];
            for (int i = 0; i < txs.Length; i++)
                txs[i] = TestUtils.CreateRandomHashTransaction();
            var msg = new RecoveryMessage
            {
                ChangeViewMessages = new Dictionary<int, RecoveryMessage.ChangeViewPayloadCompact>()
                {
                    {
                        0,
                        new RecoveryMessage.ChangeViewPayloadCompact
                        {
                            ValidatorIndex = 0,
                            OriginalViewNumber = 9,
                            Timestamp = 6,
                            InvocationScript = new[] { (byte)'A' }
                        }
                    },
                    {
                        1,
                        new RecoveryMessage.ChangeViewPayloadCompact
                        {
                            ValidatorIndex = 1,
                            OriginalViewNumber = 7,
                            Timestamp = 5,
                            InvocationScript = new[] { (byte)'B' }
                        }
                    },
                    {
                        3,
                        new RecoveryMessage.ChangeViewPayloadCompact
                        {
                            ValidatorIndex = 3,
                            OriginalViewNumber = 5,
                            Timestamp = 3,
                            InvocationScript = new[] { (byte)'C' }
                        }
                    },
                    {
                        6,
                        new RecoveryMessage.ChangeViewPayloadCompact
                        {
                            ValidatorIndex = 6,
                            OriginalViewNumber = 2,
                            Timestamp = 1,
                            InvocationScript = new[] { (byte)'D' }
                        }
                    }
                },
                PrepareRequestMessage = new PrepareRequest
                {
                    TransactionHashes = txs.Select(p => p.Hash).ToArray()
                },
                PreparationHash = new UInt256(Crypto.Hash256(new[] { (byte)'a' })),
                PreparationMessages = new Dictionary<int, RecoveryMessage.PreparationPayloadCompact>()
                {
                    {
                        0,
                        new RecoveryMessage.PreparationPayloadCompact
                        {
                            ValidatorIndex = 0,
                            InvocationScript = new[] { (byte)'t', (byte)'e' }
                        }
                    },
                    {
                        1,
                        new RecoveryMessage.PreparationPayloadCompact
                        {
                            ValidatorIndex = 1,
                            InvocationScript = new[] { (byte)'s', (byte)'t' }
                        }
                    },
                    {
                        3,
                        new RecoveryMessage.PreparationPayloadCompact
                        {
                            ValidatorIndex = 3,
                            InvocationScript = new[] { (byte)'1', (byte)'2' }
                        }
                    }
                },
                CommitMessages = new Dictionary<int, RecoveryMessage.CommitPayloadCompact>()
            };

            var copiedMsg = TestUtils.CopyMsgBySerialization(msg, new RecoveryMessage()); ;

            copiedMsg.ChangeViewMessages.Should().BeEquivalentTo(msg.ChangeViewMessages);
            copiedMsg.PrepareRequestMessage.Should().BeEquivalentTo(msg.PrepareRequestMessage);
            copiedMsg.PreparationHash.Should().Be(null);
            copiedMsg.PreparationMessages.Should().BeEquivalentTo(msg.PreparationMessages);
            copiedMsg.CommitMessages.Count.Should().Be(0);
        }
Пример #4
0
        public void TestSerializeAndDeserializeConsensusContext()
        {
            var consensusContext = new ConsensusContext(null, null)
            {
                Block = new Block
                {
                    PrevHash = Blockchain.GenesisBlock.Hash,
                    Index = 1,
                    Timestamp = 4244941711,
                    NextConsensus = UInt160.Parse("5555AAAA5555AAAA5555AAAA5555AAAA5555AAAA"),
                    ConsensusData = new ConsensusData
                    {
                        PrimaryIndex = 6
                    }
                },
                ViewNumber = 2,
                Validators = new ECPoint[7]
                {
                    ECPoint.Parse("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70", Neo.Cryptography.ECC.ECCurve.Secp256r1),
                    ECPoint.Parse("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d", Neo.Cryptography.ECC.ECCurve.Secp256r1),
                    ECPoint.Parse("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e", Neo.Cryptography.ECC.ECCurve.Secp256r1),
                    ECPoint.Parse("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554", Neo.Cryptography.ECC.ECCurve.Secp256r1),
                    ECPoint.Parse("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093", Neo.Cryptography.ECC.ECCurve.Secp256r1),
                    ECPoint.Parse("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c", Neo.Cryptography.ECC.ECCurve.Secp256r1),
                    ECPoint.Parse("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a", Neo.Cryptography.ECC.ECCurve.Secp256r1)
                },
                MyIndex = -1
            };
            var testTx1 = TestUtils.CreateRandomHashTransaction();
            var testTx2 = TestUtils.CreateRandomHashTransaction();

            int txCountToInlcude = 256;
            consensusContext.TransactionHashes = new UInt256[txCountToInlcude];

            Transaction[] txs = new Transaction[txCountToInlcude];
            for (int i = 0; i < txCountToInlcude; i++)
            {
                txs[i] = TestUtils.CreateRandomHashTransaction();
                consensusContext.TransactionHashes[i] = txs[i].Hash;
            }
            // consensusContext.TransactionHashes = new UInt256[2] {testTx1.Hash, testTx2.Hash};
            consensusContext.Transactions = txs.ToDictionary(p => p.Hash);

            consensusContext.PreparationPayloads = new ConsensusPayload[consensusContext.Validators.Length];
            var prepareRequestMessage = new PrepareRequest
            {
                TransactionHashes = consensusContext.TransactionHashes,
                Timestamp = 23
            };
            consensusContext.PreparationPayloads[6] = MakeSignedPayload(consensusContext, prepareRequestMessage, 6, new[] { (byte)'3', (byte)'!' });
            consensusContext.PreparationPayloads[0] = MakeSignedPayload(consensusContext, new PrepareResponse { PreparationHash = consensusContext.PreparationPayloads[6].Hash }, 0, new[] { (byte)'t', (byte)'e' });
            consensusContext.PreparationPayloads[1] = MakeSignedPayload(consensusContext, new PrepareResponse { PreparationHash = consensusContext.PreparationPayloads[6].Hash }, 1, new[] { (byte)'s', (byte)'t' });
            consensusContext.PreparationPayloads[2] = null;
            consensusContext.PreparationPayloads[3] = MakeSignedPayload(consensusContext, new PrepareResponse { PreparationHash = consensusContext.PreparationPayloads[6].Hash }, 3, new[] { (byte)'1', (byte)'2' });
            consensusContext.PreparationPayloads[4] = null;
            consensusContext.PreparationPayloads[5] = null;

            consensusContext.CommitPayloads = new ConsensusPayload[consensusContext.Validators.Length];
            using (SHA256 sha256 = SHA256.Create())
            {
                consensusContext.CommitPayloads[3] = MakeSignedPayload(consensusContext, new Commit { Signature = sha256.ComputeHash(testTx1.Hash.ToArray()).Concat(sha256.ComputeHash(testTx1.Hash.ToArray())).ToArray() }, 3, new[] { (byte)'3', (byte)'4' });
                consensusContext.CommitPayloads[6] = MakeSignedPayload(consensusContext, new Commit { Signature = sha256.ComputeHash(testTx2.Hash.ToArray()).Concat(sha256.ComputeHash(testTx2.Hash.ToArray())).ToArray() }, 3, new[] { (byte)'6', (byte)'7' });
            }

            consensusContext.Block.Timestamp = TimeProvider.Current.UtcNow.ToTimestampMS();

            consensusContext.ChangeViewPayloads = new ConsensusPayload[consensusContext.Validators.Length];
            consensusContext.ChangeViewPayloads[0] = MakeSignedPayload(consensusContext, new ChangeView { ViewNumber = 1, Timestamp = 6 }, 0, new[] { (byte)'A' });
            consensusContext.ChangeViewPayloads[1] = MakeSignedPayload(consensusContext, new ChangeView { ViewNumber = 1, Timestamp = 5 }, 1, new[] { (byte)'B' });
            consensusContext.ChangeViewPayloads[2] = null;
            consensusContext.ChangeViewPayloads[3] = MakeSignedPayload(consensusContext, new ChangeView { ViewNumber = 1, Timestamp = uint.MaxValue }, 3, new[] { (byte)'C' });
            consensusContext.ChangeViewPayloads[4] = null;
            consensusContext.ChangeViewPayloads[5] = null;
            consensusContext.ChangeViewPayloads[6] = MakeSignedPayload(consensusContext, new ChangeView { ViewNumber = 1, Timestamp = 1 }, 6, new[] { (byte)'D' });

            consensusContext.LastChangeViewPayloads = new ConsensusPayload[consensusContext.Validators.Length];

            var copiedContext = TestUtils.CopyMsgBySerialization(consensusContext, new ConsensusContext(null, null));

            copiedContext.Block.PrevHash.Should().Be(consensusContext.Block.PrevHash);
            copiedContext.Block.Index.Should().Be(consensusContext.Block.Index);
            copiedContext.ViewNumber.Should().Be(consensusContext.ViewNumber);
            copiedContext.Validators.Should().BeEquivalentTo(consensusContext.Validators);
            copiedContext.MyIndex.Should().Be(consensusContext.MyIndex);
            copiedContext.Block.ConsensusData.PrimaryIndex.Should().Be(consensusContext.Block.ConsensusData.PrimaryIndex);
            copiedContext.Block.Timestamp.Should().Be(consensusContext.Block.Timestamp);
            copiedContext.Block.NextConsensus.Should().Be(consensusContext.Block.NextConsensus);
            copiedContext.TransactionHashes.Should().BeEquivalentTo(consensusContext.TransactionHashes);
            copiedContext.Transactions.Should().BeEquivalentTo(consensusContext.Transactions);
            copiedContext.Transactions.Values.Should().BeEquivalentTo(consensusContext.Transactions.Values);
            copiedContext.PreparationPayloads.Should().BeEquivalentTo(consensusContext.PreparationPayloads);
            copiedContext.CommitPayloads.Should().BeEquivalentTo(consensusContext.CommitPayloads);
            copiedContext.ChangeViewPayloads.Should().BeEquivalentTo(consensusContext.ChangeViewPayloads);
        }
Пример #5
0
        public void Test_Common()
        {
            using (GDMIndividualAttribute customEvent = new GDMIndividualAttribute(null)) {
                Assert.IsNotNull(customEvent);

                Assert.IsNotNull(customEvent.Address);

                customEvent.Date.ParseString("28 DEC 1990");
                string dateTest = "28.12.1990";
                Assert.AreEqual(TestUtils.ParseDT(dateTest), customEvent.Date.GetDateTime());
                Assert.AreEqual(1990, customEvent.GetChronologicalYear());

                Assert.AreEqual(TestUtils.ParseDT(dateTest), customEvent.Date.Date);
                customEvent.Place.ParseString("Ivanovo");
                Assert.AreEqual("Ivanovo", customEvent.Place.StringValue);

                Assert.IsNotNull(customEvent.Place);

                customEvent.Agency = "test agency";
                Assert.AreEqual("test agency", customEvent.Agency);

                customEvent.Classification = "test type";
                Assert.AreEqual("test type", customEvent.Classification);

                customEvent.Cause = "test cause";
                Assert.AreEqual("test cause", customEvent.Cause);

                customEvent.ReligiousAffilation = "test aff";
                Assert.AreEqual("test aff", customEvent.ReligiousAffilation);

                customEvent.Restriction = GDMRestriction.rnLocked;
                Assert.AreEqual(GDMRestriction.rnLocked, customEvent.Restriction);


                GDMLines strs = new GDMLines("test");
                customEvent.PhysicalDescription = strs;
                Assert.AreEqual(strs.Text, customEvent.PhysicalDescription.Text);

                customEvent.Address.AddEmailAddress("email");
                Assert.AreEqual("email", customEvent.Address.EmailAddresses[0].StringValue);
            }

            using (GDMIndividualEvent customEvent = new GDMIndividualEvent(null)) {
                Assert.IsNotNull(customEvent);

                // stream test
                customEvent.SetName(GEDCOMTagName.BIRT);
                customEvent.Date.ParseString("20 SEP 1970");
                customEvent.Place.StringValue   = "test place";
                customEvent.Agency              = "Agency";
                customEvent.Classification      = "custom";
                customEvent.ReligiousAffilation = "rel_aff";
                customEvent.Cause = "Cause";
                customEvent.Address.AddressLine1 = "adr1";
                customEvent.Restriction          = GDMRestriction.rnConfidential;

                var note = new GDMNotes(customEvent);
                note.Lines.Text = "event notes";
                customEvent.Notes.Add(note);

                var sourCit = new GDMSourceCitation(customEvent);
                sourCit.Description.Text = "event sour desc";
                customEvent.SourceCitations.Add(sourCit);

                var mmLink = new GDMMultimediaLink(customEvent);
                mmLink.Title = "event media title";
                customEvent.MultimediaLinks.Add(mmLink);

                using (GDMIndividualEvent copyEvent = new GDMIndividualEvent(null)) {
                    Assert.IsNotNull(copyEvent);
                    copyEvent.Assign(customEvent);

                    string buf1 = TestUtils.GetTagStreamText(copyEvent, 0);
                    Assert.AreEqual("0 BIRT\r\n" +
                                    "1 TYPE custom\r\n" +
                                    "1 DATE 20 SEP 1970\r\n" +
                                    "1 PLAC test place\r\n" +
                                    "1 ADDR\r\n" +
                                    "2 ADR1 adr1\r\n" +
                                    "1 CAUS Cause\r\n" +
                                    "1 AGNC Agency\r\n" +
                                    "1 RELI rel_aff\r\n" +
                                    "1 RESN confidential\r\n" +
                                    "1 NOTE event notes\r\n" +
                                    "1 SOUR event sour desc\r\n" +
                                    "1 OBJE\r\n" +
                                    "2 TITL event media title\r\n", buf1);
                }

                customEvent.Address.AddEmailAddress("email");
                Assert.AreEqual("email", customEvent.Address.EmailAddresses[0].StringValue);
            }

            using (GDMFamilyEvent customEvent = new GDMFamilyEvent(null)) {
                Assert.IsNotNull(customEvent);

                customEvent.Address.AddEmailAddress("email");
                Assert.AreEqual("email", customEvent.Address.EmailAddresses[0].StringValue);
            }
        }
Пример #6
0
 public IllusionTests(TestUtils utils, ITestOutputHelper output)
 {
     utils.SetOutputHelper(output);
 }
Пример #7
0
        public void CreateForumWithEmptyIds()
        {
            NForum.CQS.Commands.Forums.CreateForumCommand create = new CQS.Commands.Forums.CreateForumCommand {
                CategoryId    = String.Empty,
                ParentForumId = String.Empty,
                Name          = "hep"
            };

            NForum.CQS.Validators.Forums.CreateForumValidator validator = new CQS.Validators.Forums.CreateForumValidator(TestUtils.GetInt32IdValidator());

            ValidationResult result = validator.Validate(create);

            result.IsValid.Should().Be(false, "Empty ids is not allowed");

            create.CategoryId    = "    ";
            create.ParentForumId = "    ";
            result = validator.Validate(create);
            result.IsValid.Should().Be(false, "Empty ids is not allowed");

            create.CategoryId    = "\t";
            create.ParentForumId = "\t";
            result = validator.Validate(create);
            result.IsValid.Should().Be(false, "Empty ids is not allowed");

            create.CategoryId    = null;
            create.ParentForumId = null;
            result = validator.Validate(create);
            result.IsValid.Should().Be(false, "Empty ids is not allowed");
        }
Пример #8
0
        public void MoveForumWithIdAndEmptyDestinationIds()
        {
            NForum.CQS.Commands.Forums.MoveForumCommand delete = new CQS.Commands.Forums.MoveForumCommand {
                Id = 32456.ToString(),
                DestinationCategoryId = String.Empty,
                DestinationForumId    = String.Empty
            };

            NForum.CQS.Validators.Forums.MoveForumValidator validator = new CQS.Validators.Forums.MoveForumValidator(TestUtils.GetInt32IdValidator());

            ValidationResult result = validator.Validate(delete);

            result.IsValid.Should().Be(false, "No destination was given");
        }
Пример #9
0
 public void TestPerformanceMemoryCache() => TestUtils.TestPerformance(this.TestPerformanceMemoryCacheInternal);
Пример #10
0
 public MemoryCacheTests()
 {
     this.app = TestUtils.CreateTestApp(typeof(MemoryCachingModule));
     this.app.Start();
 }
Пример #11
0
 protected override Task <string> GetConnectionString()
 {
     TestUtils.CheckForAzureStorage();
     return(Task.FromResult(TestDefaultConfiguration.DataConnectionString));
 }
Пример #12
0
        public void Test_Common()
        {
            using (GDMAddress addr = new GDMAddress()) {
                Assert.IsNotNull(addr, "addr != null");

                addr.SetAddressText("test");
                Assert.AreEqual("test", addr.Lines.Text.Trim());

                addr.Lines.Text = "This\r\naddress\r\ntest";
                Assert.AreEqual("This\r\naddress\r\ntest", addr.Lines.Text.Trim());
                Assert.AreEqual("This", addr.Lines[0]);
                Assert.AreEqual("address", addr.Lines[1]);
                Assert.AreEqual("test", addr.Lines[2]);

                addr.AddPhoneNumber("8 911 101 99 99");
                Assert.AreEqual("8 911 101 99 99", addr.PhoneNumbers[0].StringValue);

                addr.AddEmailAddress("*****@*****.**");
                Assert.AreEqual("*****@*****.**", addr.EmailAddresses[0].StringValue);

                addr.AddFaxNumber("abrakadabra");
                Assert.AreEqual("abrakadabra", addr.FaxNumbers[0].StringValue);

                addr.AddWebPage("http://test.com");
                Assert.AreEqual("http://test.com", addr.WebPages[0].StringValue);

                addr.AddPhoneNumber("8 911 101 33 33");
                Assert.AreEqual("8 911 101 33 33", addr.PhoneNumbers[1].StringValue);

                addr.AddEmailAddress("*****@*****.**");
                Assert.AreEqual("*****@*****.**", addr.EmailAddresses[1].StringValue);

                addr.AddFaxNumber("abrakadabra");
                Assert.AreEqual("abrakadabra", addr.FaxNumbers[1].StringValue);

                addr.AddWebPage("http://test.ru");
                Assert.AreEqual("http://test.ru", addr.WebPages[1].StringValue);

                //

                addr.AddressLine1 = "test1";
                Assert.AreEqual("test1", addr.AddressLine1);

                addr.AddressLine2 = "test2";
                Assert.AreEqual("test2", addr.AddressLine2);

                addr.AddressLine3 = "test3";
                Assert.AreEqual("test3", addr.AddressLine3);

                addr.AddressCity = "test4";
                Assert.AreEqual("test4", addr.AddressCity);

                addr.AddressState = "test5";
                Assert.AreEqual("test5", addr.AddressState);

                addr.AddressCountry = "test6";
                Assert.AreEqual("test6", addr.AddressCountry);

                addr.AddressPostalCode = "test7";
                Assert.AreEqual("test7", addr.AddressPostalCode);

                using (GDMAddress addr2 = new GDMAddress()) {
                    Assert.Throws(typeof(ArgumentException), () => {
                        addr2.Assign(null);
                    });

                    addr2.Assign(addr);

                    var iRec = new GDMIndividualRecord(null);
                    var evt  = new GDMIndividualEvent();
                    evt.SetName("BIRT");
                    iRec.Events.Add(evt);
                    evt.Address.Assign(addr);

                    string buf = TestUtils.GetTagStreamText(iRec, 0);
                    Assert.AreEqual("0 INDI\r\n" +
                                    "1 SEX U\r\n" +
                                    "1 BIRT\r\n" +
                                    "2 ADDR This\r\n" +
                                    "3 CONT address\r\n" +
                                    "3 CONT test\r\n" +
                                    "3 ADR1 test1\r\n" +
                                    "3 ADR2 test2\r\n" +
                                    "3 ADR3 test3\r\n" +
                                    "3 CITY test4\r\n" +
                                    "3 STAE test5\r\n" +
                                    "3 CTRY test6\r\n" +
                                    "3 POST test7\r\n" +
                                    "2 PHON 8 911 101 99 99\r\n" +
                                    "2 PHON 8 911 101 33 33\r\n" +
                                    "2 EMAIL [email protected]\r\n" +
                                    "2 EMAIL [email protected]\r\n" +
                                    "2 FAX abrakadabra\r\n" +
                                    "2 FAX abrakadabra\r\n" +
                                    "2 WWW http://test.com\r\n" +
                                    "2 WWW http://test.ru\r\n", buf);

                    Assert.AreEqual("This\r\naddress\r\ntest", addr2.Lines.Text.Trim());
                    Assert.AreEqual("8 911 101 99 99", addr2.PhoneNumbers[0].StringValue);
                    Assert.AreEqual("*****@*****.**", addr2.EmailAddresses[0].StringValue);
                    Assert.AreEqual("abrakadabra", addr2.FaxNumbers[0].StringValue);
                    Assert.AreEqual("http://test.com", addr2.WebPages[0].StringValue);
                    Assert.AreEqual("8 911 101 33 33", addr2.PhoneNumbers[1].StringValue);
                    Assert.AreEqual("*****@*****.**", addr2.EmailAddresses[1].StringValue);
                    Assert.AreEqual("abrakadabra", addr2.FaxNumbers[1].StringValue);
                    Assert.AreEqual("http://test.ru", addr2.WebPages[1].StringValue);
                    Assert.AreEqual("test1", addr2.AddressLine1);
                    Assert.AreEqual("test2", addr2.AddressLine2);
                    Assert.AreEqual("test3", addr2.AddressLine3);
                    Assert.AreEqual("test4", addr2.AddressCity);
                    Assert.AreEqual("test5", addr2.AddressState);
                    Assert.AreEqual("test6", addr2.AddressCountry);
                    Assert.AreEqual("test7", addr2.AddressPostalCode);
                }

                addr.SetAddressArray(new string[] { "test11", "test21", "test31" });
                Assert.AreEqual("test11", addr.Lines[0]);
                Assert.AreEqual("test21", addr.Lines[1]);
                Assert.AreEqual("test31", addr.Lines[2]);

                Assert.IsFalse(addr.IsEmpty());
                addr.Clear();
                Assert.IsTrue(addr.IsEmpty());
            }
        }
Пример #13
0
        public void ProceduresSchemaProviderTest(
            [IncludeDataSources(false, ProviderName.MySql, TestProvName.MariaDB, TestProvName.MySql57)] string context,
            [ValueSource(nameof(ProcedureTestCases))] ProcedureSchema expectedProc)
        {
            // TODO: add aggregate/udf functions test cases
            using (var db = (DataConnection)GetDataContext(context))
            {
                expectedProc.CatalogName = TestUtils.GetDatabaseName(db);

                var schema = db.DataProvider.GetSchemaProvider().GetSchema(db, TestUtils.GetDefaultSchemaOptions(context));

                var procedures = schema.Procedures.Where(_ => _.ProcedureName == expectedProc.ProcedureName).ToList();

                Assert.AreEqual(1, procedures.Count);

                var procedure = procedures[0];

                Assert.AreEqual(expectedProc.CatalogName, procedure.CatalogName);
                Assert.AreEqual(expectedProc.SchemaName, procedure.SchemaName);
                Assert.AreEqual(expectedProc.MemberName, procedure.MemberName);
                Assert.AreEqual(expectedProc.IsTableFunction, procedure.IsTableFunction);
                Assert.AreEqual(expectedProc.IsAggregateFunction, procedure.IsAggregateFunction);
                Assert.AreEqual(expectedProc.IsDefaultSchema, procedure.IsDefaultSchema);
                Assert.AreEqual(expectedProc.IsLoaded, procedure.IsLoaded);

                Assert.IsNull(procedure.ResultException);

                Assert.AreEqual(expectedProc.Parameters.Count, procedure.Parameters.Count);

                for (var i = 0; i < procedure.Parameters.Count; i++)
                {
                    var actualParam   = procedure.Parameters[i];
                    var expectedParam = expectedProc.Parameters[i];

                    Assert.IsNotNull(expectedParam);

                    Assert.AreEqual(expectedParam.SchemaName, actualParam.SchemaName);
                    Assert.AreEqual(expectedParam.ParameterName, actualParam.ParameterName);
                    Assert.AreEqual(expectedParam.SchemaType, actualParam.SchemaType);
                    Assert.AreEqual(expectedParam.IsIn, actualParam.IsIn);
                    Assert.AreEqual(expectedParam.IsOut, actualParam.IsOut);
                    Assert.AreEqual(expectedParam.IsResult, actualParam.IsResult);
                    Assert.AreEqual(expectedParam.Size, actualParam.Size);
                    Assert.AreEqual(expectedParam.ParameterType, actualParam.ParameterType);
                    Assert.AreEqual(expectedParam.SystemType, actualParam.SystemType);
                    Assert.AreEqual(expectedParam.DataType, actualParam.DataType);
                    Assert.AreEqual(expectedParam.ProviderSpecificType, actualParam.ProviderSpecificType);
                }

                if (expectedProc.ResultTable == null)
                {
                    Assert.IsNull(procedure.ResultTable);

                    // maybe it is worth changing
                    Assert.IsNull(procedure.SimilarTables);
                }
                else
                {
                    Assert.IsNotNull(procedure.ResultTable);

                    var expectedTable = expectedProc.ResultTable;
                    var actualTable   = procedure.ResultTable;

                    Assert.AreEqual(expectedTable.ID, actualTable.ID);
                    Assert.AreEqual(expectedTable.CatalogName, actualTable.CatalogName);
                    Assert.AreEqual(expectedTable.SchemaName, actualTable.SchemaName);
                    Assert.AreEqual(expectedTable.TableName, actualTable.TableName);
                    Assert.AreEqual(expectedTable.Description, actualTable.Description);
                    Assert.AreEqual(expectedTable.IsDefaultSchema, actualTable.IsDefaultSchema);
                    Assert.AreEqual(expectedTable.IsView, actualTable.IsView);
                    Assert.AreEqual(expectedTable.IsProcedureResult, actualTable.IsProcedureResult);
                    Assert.AreEqual(expectedTable.TypeName, actualTable.TypeName);
                    Assert.AreEqual(expectedTable.IsProviderSpecific, actualTable.IsProviderSpecific);

                    Assert.IsNotNull(actualTable.ForeignKeys);
                    Assert.IsEmpty(actualTable.ForeignKeys);

                    Assert.AreEqual(expectedTable.Columns.Count, actualTable.Columns.Count);

                    foreach (var actualColumn in actualTable.Columns)
                    {
                        var expectedColumn = expectedTable.Columns
                                             .Where(_ => _.ColumnName == actualColumn.ColumnName)
                                             .SingleOrDefault();

                        Assert.IsNotNull(expectedColumn);

                        Assert.AreEqual(expectedColumn.ColumnType, actualColumn.ColumnType);
                        Assert.AreEqual(expectedColumn.IsNullable, actualColumn.IsNullable);
                        Assert.AreEqual(expectedColumn.IsIdentity, actualColumn.IsIdentity);
                        Assert.AreEqual(expectedColumn.IsPrimaryKey, actualColumn.IsPrimaryKey);
                        Assert.AreEqual(expectedColumn.PrimaryKeyOrder, actualColumn.PrimaryKeyOrder);
                        Assert.AreEqual(expectedColumn.Description, actualColumn.Description);
                        Assert.AreEqual(expectedColumn.MemberName, actualColumn.MemberName);
                        Assert.AreEqual(expectedColumn.MemberType, actualColumn.MemberType);
                        Assert.AreEqual(expectedColumn.ProviderSpecificType, actualColumn.ProviderSpecificType);
                        Assert.AreEqual(expectedColumn.SystemType, actualColumn.SystemType);
                        Assert.AreEqual(expectedColumn.DataType, actualColumn.DataType);
                        Assert.AreEqual(expectedColumn.SkipOnInsert, actualColumn.SkipOnInsert);
                        Assert.AreEqual(expectedColumn.SkipOnUpdate, actualColumn.SkipOnUpdate);
                        Assert.AreEqual(expectedColumn.Length, actualColumn.Length);
                        Assert.AreEqual(expectedColumn.Precision, actualColumn.Precision);
                        Assert.AreEqual(expectedColumn.Scale, actualColumn.Scale);
                        Assert.AreEqual(actualTable, actualColumn.Table);
                    }

                    Assert.IsNotNull(procedure.SimilarTables);

                    foreach (var table in procedure.SimilarTables)
                    {
                        var tbl = expectedProc.SimilarTables
                                  .Where(_ => _.TableName == table.TableName)
                                  .SingleOrDefault();

                        Assert.IsNotNull(tbl);
                    }
                }
            }
        }
        public void PreProc_EndToEnd_SuccessCase()
        {
            // Checks end-to-end happy path for the pre-processor i.e.
            // * arguments are parsed
            // * targets are installed
            // * server properties are fetched
            // * rulesets are generated
            // * config file is created

            // Arrange
            var workingDir = TestUtils.CreateTestSpecificFolder(TestContext);
            var logger     = new TestLogger();

            // Configure the server
            var mockServer = new MockSonarQubeServer();

            var data = mockServer.Data;

            data.ServerProperties.Add("server.key", "server value 1");

            data.Languages.Add("cs");
            data.Languages.Add("vbnet");
            data.Languages.Add("another_plugin");

            data.AddQualityProfile("qp1", "cs", null)
            .AddProject("key")
            .AddRule(new ActiveRule("csharpsquid", "cs.rule3"));

            data.AddQualityProfile("qp2", "vbnet", null)
            .AddProject("key")
            .AddRule(new ActiveRule("vbnet", "vb.rule3"));

            var mockAnalyzerProvider = new MockRoslynAnalyzerProvider
            {
                SettingsToReturn = new AnalyzerSettings
                {
                    RuleSetFilePath = "c:\\xxx.ruleset"
                }
            };

            var mockTargetsInstaller = new Mock <ITargetsInstaller>();
            var mockFactory          = new MockObjectFactory(mockServer, mockTargetsInstaller.Object, mockAnalyzerProvider);

            TeamBuildSettings settings;

            using (PreprocessTestUtils.CreateValidNonTeamBuildScope())
                using (new WorkingDirectoryScope(workingDir))
                {
                    settings = TeamBuildSettings.GetSettingsFromEnvironment(new TestLogger());
                    Assert.IsNotNull(settings, "Test setup error: TFS environment variables have not been set correctly");
                    Assert.AreEqual(BuildEnvironment.NotTeamBuild, settings.BuildEnvironment, "Test setup error: build environment was not set correctly");

                    var preProcessor = new TeamBuildPreProcessor(mockFactory, logger);

                    // Act
                    var success = preProcessor.Execute(CreateValidArgs("key", "name", "1.0"));
                    Assert.IsTrue(success, "Expecting the pre-processing to complete successfully");
                }

            // Assert
            AssertDirectoriesCreated(settings);

            mockTargetsInstaller.Verify(x => x.InstallLoaderTargets(logger, workingDir), Times.Once());
            mockServer.AssertMethodCalled("GetProperties", 1);
            mockServer.AssertMethodCalled("GetAllLanguages", 1);
            mockServer.AssertMethodCalled("TryGetQualityProfile", 2); // C# and VBNet
            mockServer.AssertMethodCalled("GetActiveRules", 2);       // C# and VBNet
            mockServer.AssertMethodCalled("GetInactiveRules", 2);     // C# and VBNet

            AssertAnalysisConfig(settings.AnalysisConfigFilePath, 2, logger);
        }
        public void PreProc_NoProject()
        {
            // Arrange
            var workingDir = TestUtils.CreateTestSpecificFolder(TestContext);
            var logger     = new TestLogger();

            // Configure the server
            var mockServer = new MockSonarQubeServer();

            var data = mockServer.Data;

            data.ServerProperties.Add("server.key", "server value 1");

            data.Languages.Add("cs");
            data.Languages.Add("vbnet");
            data.Languages.Add("another_plugin");

            data.AddQualityProfile("qp1", "cs", null)
            .AddProject("invalid")
            .AddRule(new ActiveRule("fxcop", "cs.rule1"))
            .AddRule(new ActiveRule("fxcop", "cs.rule2"));

            data.AddQualityProfile("qp2", "vbnet", null)
            .AddProject("invalid")
            .AddRule(new ActiveRule("fxcop-vbnet", "vb.rule1"))
            .AddRule(new ActiveRule("fxcop-vbnet", "vb.rule2"));

            var mockAnalyzerProvider = new MockRoslynAnalyzerProvider
            {
                SettingsToReturn = new AnalyzerSettings
                {
                    RuleSetFilePath = "c:\\xxx.ruleset"
                }
            };

            var mockTargetsInstaller = new Mock <ITargetsInstaller>();
            var mockFactory          = new MockObjectFactory(mockServer, mockTargetsInstaller.Object, mockAnalyzerProvider);

            TeamBuildSettings settings;

            using (PreprocessTestUtils.CreateValidNonTeamBuildScope())
                using (new WorkingDirectoryScope(workingDir))
                {
                    settings = TeamBuildSettings.GetSettingsFromEnvironment(new TestLogger());
                    Assert.IsNotNull(settings, "Test setup error: TFS environment variables have not been set correctly");
                    Assert.AreEqual(BuildEnvironment.NotTeamBuild, settings.BuildEnvironment, "Test setup error: build environment was not set correctly");

                    var preProcessor = new TeamBuildPreProcessor(mockFactory, logger);

                    // Act
                    var success = preProcessor.Execute(CreateValidArgs("key", "name", "1.0", null));
                    Assert.IsTrue(success, "Expecting the pre-processing to complete successfully");
                }

            // Assert
            AssertDirectoriesCreated(settings);

            mockTargetsInstaller.Verify(x => x.InstallLoaderTargets(logger, workingDir), Times.Once());
            mockServer.AssertMethodCalled("GetProperties", 1);
            mockServer.AssertMethodCalled("GetAllLanguages", 1);
            mockServer.AssertMethodCalled("TryGetQualityProfile", 2); // C# and VBNet
            mockServer.AssertMethodCalled("GetActiveRules", 0);       // no quality profile assigned to project
            mockServer.AssertMethodCalled("GetInactiveRules", 0);

            AssertAnalysisConfig(settings.AnalysisConfigFilePath, 0, logger);

            // only contains SonarQubeAnalysisConfig (no rulesets or aditional files)
            AssertDirectoryContains(settings.SonarConfigDirectory, Path.GetFileName(settings.AnalysisConfigFilePath));
        }
Пример #16
0
        public void MoveForumWithEmptyId()
        {
            NForum.CQS.Commands.Forums.MoveForumCommand delete = new CQS.Commands.Forums.MoveForumCommand {
                Id = String.Empty,
                DestinationCategoryId = 32435657.ToString()
            };

            NForum.CQS.Validators.Forums.MoveForumValidator validator = new CQS.Validators.Forums.MoveForumValidator(TestUtils.GetInt32IdValidator());

            ValidationResult result = validator.Validate(delete);

            result.IsValid.Should().Be(false, "No Id was provided");
        }
Пример #17
0
 public void FixtureSetUp()
 {
     _ignite = Ignition.Start(TestUtils.GetTestConfiguration());
 }
Пример #18
0
        public void MoveForumWithCategoryEmpty()
        {
            NForum.CQS.Commands.Forums.MoveForumCommand delete = new CQS.Commands.Forums.MoveForumCommand {
                Id = 3454657.ToString(),
                DestinationForumId = 32435657.ToString()
            };

            NForum.CQS.Validators.Forums.MoveForumValidator validator = new CQS.Validators.Forums.MoveForumValidator(TestUtils.GetInt32IdValidator());

            ValidationResult result = validator.Validate(delete);

            result.IsValid.Should().Be(true, "Ids was provided");
        }
Пример #19
0
 public void TestSetup()
 {
     _uniqueKsName = TestUtils.GetUniqueKeyspaceName().ToLowerInvariant();
     _session.CreateKeyspace(_uniqueKsName);
     _session.ChangeKeyspace(_uniqueKsName);
 }
Пример #20
0
        public void UpdateForumWithEmptyNameAndId()
        {
            NForum.CQS.Commands.Forums.UpdateForumCommand update = new CQS.Commands.Forums.UpdateForumCommand {
                Id   = String.Empty,
                Name = String.Empty
            };

            NForum.CQS.Validators.Forums.UpdateForumValidator validator = new NForum.CQS.Validators.Forums.UpdateForumValidator(TestUtils.GetInt32IdValidator());

            ValidationResult result = validator.Validate(update);

            result.IsValid.Should().Be(false, "An empty id/name is not allowed");
            result.Errors.Count().Should().Be(2, "An empty name and/or id is not allowed");

            update.Id   = null;
            update.Name = null;
            result      = validator.Validate(update);
            result.IsValid.Should().Be(false, "An empty id/name is not allowed");
            result.Errors.Count().Should().Be(2, "An empty name and/or id is not allowed");

            update.Id   = "\t";
            update.Name = "\t";
            result      = validator.Validate(update);
            result.IsValid.Should().Be(false, "An empty id/name is not allowed");
            result.Errors.Count().Should().Be(2, "An empty name and/or id is not allowed");

            update.Id   = 2153.ToString();
            update.Name = String.Empty;
            result      = validator.Validate(update);
            result.IsValid.Should().Be(false, "An empty name is not allowed");

            update.Id   = String.Empty;
            update.Name = "my name";
            result      = validator.Validate(update);
            result.IsValid.Should().Be(false, "An empty id is not allowed");
        }
Пример #21
0
 public void SetupHarness()
 {
     TestUtils.Initialize();
 }
Пример #22
0
 public void SetUp()
 {
     TestUtils.InitGEDCOMProviderTest();
     fContext = TestUtils.CreateContext();
     TestUtils.FillContext(fContext);
 }
Пример #23
0
        public void DeleteCategoryWithEmptyId()
        {
            NForum.CQS.Commands.Forums.DeleteForumCommand delete = new NForum.CQS.Commands.Forums.DeleteForumCommand {
                Id = String.Empty
            };

            NForum.CQS.Validators.Forums.DeleteForumValidator validator = new NForum.CQS.Validators.Forums.DeleteForumValidator(TestUtils.GetInt32IdValidator());

            ValidationResult result = validator.Validate(delete);

            result.IsValid.Should().Be(false, "An empty id is not allowed");

            delete.Id = "\t";
            result    = validator.Validate(delete);
            result.IsValid.Should().Be(false, "An empty id is not allowed");

            delete.Id = null;
            result    = validator.Validate(delete);
            result.IsValid.Should().Be(false, "An empty id is not allowed");

            delete.Id = "heherje";
            result    = validator.Validate(delete);
            result.IsValid.Should().Be(false, "Id must be an Int32 value");
        }
Пример #24
0
        public void ConsensusService_SingleNodeActors_OnStart_PrepReq_PrepResponses_Commits()
        {
            var mockWallet = new Mock<Wallet>();
            mockWallet.Setup(p => p.GetAccount(It.IsAny<UInt160>())).Returns<UInt160>(p => new TestWalletAccount(p));
            Console.WriteLine($"\n(UT-Consensus) Wallet is: {mockWallet.Object.GetAccount(UInt160.Zero).GetKey().PublicKey}");

            var mockContext = new Mock<ConsensusContext>(mockWallet.Object, Blockchain.Singleton.Store);
            mockContext.Object.LastSeenMessage = new int[] { 0, 0, 0, 0, 0, 0, 0 };

            KeyPair[] kp_array = new KeyPair[7]
                {
                    UT_Crypto.generateKey(32), // not used, kept for index consistency, didactically
                    UT_Crypto.generateKey(32),
                    UT_Crypto.generateKey(32),
                    UT_Crypto.generateKey(32),
                    UT_Crypto.generateKey(32),
                    UT_Crypto.generateKey(32),
                    UT_Crypto.generateKey(32)
                };

            var timeValues = new[] {
              new DateTime(1980, 06, 01, 0, 0, 1, 001, DateTimeKind.Utc),  // For tests, used below
              new DateTime(1980, 06, 01, 0, 0, 3, 001, DateTimeKind.Utc),  // For receiving block
              new DateTime(1980, 05, 01, 0, 0, 5, 001, DateTimeKind.Utc), // For Initialize
              new DateTime(1980, 06, 01, 0, 0, 15, 001, DateTimeKind.Utc), // unused
            };
            for (int i = 0; i < timeValues.Length; i++)
                Console.WriteLine($"time {i}: {timeValues[i].ToString()} ");
            ulong defaultTimestamp = 328665601001;   // GMT: Sunday, June 1, 1980 12:00:01.001 AM
                                                     // check basic ConsensusContext
                                                     // mockConsensusContext.Object.block_received_time.ToTimestamp().Should().Be(4244941697); //1968-06-01 00:00:01
                                                     // ============================================================================
                                                     //                      creating ConsensusService actor
                                                     // ============================================================================

            int timeIndex = 0;
            var timeMock = new Mock<TimeProvider>();
            timeMock.SetupGet(tp => tp.UtcNow).Returns(() => timeValues[timeIndex]);
            //.Callback(() => timeIndex = timeIndex + 1); //Comment while index is not fixed

            TimeProvider.Current = timeMock.Object;
            TimeProvider.Current.UtcNow.ToTimestampMS().Should().Be(defaultTimestamp); //1980-06-01 00:00:15:001

            //public void Log(string message, LogLevel level)
            //create ILogPlugin for Tests
            /*
            mockConsensusContext.Setup(mr => mr.Log(It.IsAny<string>(), It.IsAny<LogLevel>()))
                         .Callback((string message, LogLevel level) => {
                                         Console.WriteLine($"CONSENSUS LOG: {message}");
                                                                   }
                                  );
             */

            // Creating a test block
            Header header = new Header();
            TestUtils.SetupHeaderWithValues(header, UInt256.Zero, out UInt256 merkRootVal, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal);
            header.Size.Should().Be(105);
            Console.WriteLine($"header {header} hash {header.Hash} {header.PrevHash} timestamp {timestampVal}");
            timestampVal.Should().Be(defaultTimestamp);
            TestProbe subscriber = CreateTestProbe();
            TestActorRef<ConsensusService> actorConsensus = ActorOfAsTestActorRef<ConsensusService>(
                                     Akka.Actor.Props.Create(() => (ConsensusService)Activator.CreateInstance(typeof(ConsensusService), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { subscriber, subscriber, mockContext.Object }, null))
                                     );

            var testPersistCompleted = new Blockchain.PersistCompleted
            {
                Block = new Block
                {
                    Version = header.Version,
                    PrevHash = header.PrevHash,
                    MerkleRoot = header.MerkleRoot,
                    Timestamp = header.Timestamp,
                    Index = header.Index,
                    NextConsensus = header.NextConsensus,
                    Transactions = new Transaction[0]
                }
            };
            Console.WriteLine("\n==========================");
            Console.WriteLine("Telling a new block to actor consensus...");
            Console.WriteLine("will trigger OnPersistCompleted without OnStart flag!");
            // OnPersist will not launch timer, we need OnStart
            actorConsensus.Tell(testPersistCompleted);
            Console.WriteLine("\n==========================");

            Console.WriteLine("\n==========================");
            Console.WriteLine("will start consensus!");
            actorConsensus.Tell(new ConsensusService.Start
            {
                IgnoreRecoveryLogs = true
            });

            Console.WriteLine("Waiting for subscriber recovery message...");
            // The next line force a waits, then, subscriber keeps running its thread
            // In the next case it waits for a Msg of type LocalNode.SendDirectly
            // As we may expect, as soon as consensus start it sends a RecoveryRequest of this aforementioned type
            var askingForInitialRecovery = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            Console.WriteLine($"Recovery Message I: {askingForInitialRecovery}");
            // Ensuring cast of type ConsensusPayload from the received message from subscriber
            ConsensusPayload initialRecoveryPayload = (ConsensusPayload)askingForInitialRecovery.Inventory;
            // Ensuring casting of type RecoveryRequest
            RecoveryRequest rrm = (RecoveryRequest)initialRecoveryPayload.ConsensusMessage;
            rrm.Timestamp.Should().Be(defaultTimestamp);

            Console.WriteLine("Waiting for backup ChangeView... ");
            var backupOnAskingChangeView = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var changeViewPayload = (ConsensusPayload)backupOnAskingChangeView.Inventory;
            ChangeView cvm = (ChangeView)changeViewPayload.ConsensusMessage;
            cvm.Timestamp.Should().Be(defaultTimestamp);
            cvm.ViewNumber.Should().Be(0);
            cvm.Reason.Should().Be(ChangeViewReason.Timeout);

            // Original Contract
            Contract originalContract = Contract.CreateMultiSigContract(mockContext.Object.M, mockContext.Object.Validators);
            Console.WriteLine($"\nORIGINAL Contract is: {originalContract.ScriptHash}");
            Console.WriteLine($"ORIGINAL NextConsensus: {mockContext.Object.Block.NextConsensus}\nENSURING values...");
            originalContract.ScriptHash.Should().Be(UInt160.Parse("0x7ab841144dcdbf228ff57f7068f795e2afd1a3c1"));
            mockContext.Object.Block.NextConsensus.Should().Be(UInt160.Parse("0x7ab841144dcdbf228ff57f7068f795e2afd1a3c1"));

            Console.WriteLine("\n==========================");
            Console.WriteLine("will trigger OnPersistCompleted again with OnStart flag!");
            actorConsensus.Tell(testPersistCompleted);
            Console.WriteLine("\n==========================");

            // Disabling flag ViewChanging by reverting cache of changeview that was sent
            mockContext.Object.ChangeViewPayloads[mockContext.Object.MyIndex] = null;
            Console.WriteLine("Forcing Failed nodes for recovery request... ");
            mockContext.Object.CountFailed.Should().Be(0);
            mockContext.Object.LastSeenMessage = new int[] { -1, -1, -1, -1, -1, -1, -1 };
            mockContext.Object.CountFailed.Should().Be(7);
            Console.WriteLine("\nWaiting for recovery due to failed nodes... ");
            var backupOnRecoveryDueToFailedNodes = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var recoveryPayload = (ConsensusPayload)backupOnRecoveryDueToFailedNodes.Inventory;
            rrm = (RecoveryRequest)recoveryPayload.ConsensusMessage;
            rrm.Timestamp.Should().Be(defaultTimestamp);

            Console.WriteLine("will create template MakePrepareRequest...");
            mockContext.Object.PrevHeader.Timestamp = defaultTimestamp;
            mockContext.Object.PrevHeader.NextConsensus.Should().Be(UInt160.Parse("0x7ab841144dcdbf228ff57f7068f795e2afd1a3c1"));
            var prepReq = mockContext.Object.MakePrepareRequest();
            var ppToSend = (PrepareRequest)prepReq.ConsensusMessage;
            // Forcing hashes to 0 because mempool is currently shared
            ppToSend.TransactionHashes = new UInt256[0];
            ppToSend.TransactionHashes.Length.Should().Be(0);
            Console.WriteLine($"\nAsserting PreparationPayloads is 1 (After MakePrepareRequest)...");
            mockContext.Object.PreparationPayloads.Count(p => p != null).Should().Be(1);
            mockContext.Object.PreparationPayloads[prepReq.ValidatorIndex] = null;

            Console.WriteLine("will tell prepare request!");
            actorConsensus.Tell(prepReq);
            Console.WriteLine("Waiting for something related to the PrepRequest...\nNothing happens...Recovery will come due to failed nodes");
            var backupOnRecoveryDueToFailedNodesII = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var recoveryPayloadII = (ConsensusPayload)backupOnRecoveryDueToFailedNodesII.Inventory;
            rrm = (RecoveryRequest)recoveryPayloadII.ConsensusMessage;
            Console.WriteLine($"\nAsserting PreparationPayloads is 0...");
            mockContext.Object.PreparationPayloads.Count(p => p != null).Should().Be(0);
            Console.WriteLine($"\nAsserting CountFailed is 6...");
            mockContext.Object.CountFailed.Should().Be(6);

            Console.WriteLine("\nFailed because it is not primary and it created the prereq...Time to adjust");
            prepReq.ValidatorIndex = 1; //simulating primary as prepreq creator (signature is skip, no problem)
            // cleaning old try with Self ValidatorIndex
            mockContext.Object.PreparationPayloads[mockContext.Object.MyIndex] = null;

            actorConsensus.Tell(prepReq);
            var OnPrepResponse = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var prepResponsePayload = (ConsensusPayload)OnPrepResponse.Inventory;
            PrepareResponse prm = (PrepareResponse)prepResponsePayload.ConsensusMessage;
            prm.PreparationHash.Should().Be(prepReq.Hash);
            Console.WriteLine("\nAsserting PreparationPayloads count is 2...");
            mockContext.Object.PreparationPayloads.Count(p => p != null).Should().Be(2);
            Console.WriteLine($"\nAsserting CountFailed is 5...");
            mockContext.Object.CountFailed.Should().Be(5);

            // Simulating CN 3
            actorConsensus.Tell(GetPayloadAndModifyValidator(prepResponsePayload, 2));
            //Waiting for RecoveryRequest for a more deterministic UT
            backupOnRecoveryDueToFailedNodes = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            recoveryPayload = (ConsensusPayload)backupOnRecoveryDueToFailedNodes.Inventory;
            rrm = (RecoveryRequest)recoveryPayload.ConsensusMessage;
            rrm.Timestamp.Should().Be(defaultTimestamp);
            //Asserts
            Console.WriteLine("\nAsserting PreparationPayloads count is 3...");
            mockContext.Object.PreparationPayloads.Count(p => p != null).Should().Be(3);
            Console.WriteLine($"\nAsserting CountFailed is 4...");
            mockContext.Object.CountFailed.Should().Be(4);

            // Simulating CN 5
            actorConsensus.Tell(GetPayloadAndModifyValidator(prepResponsePayload, 4));
            //Waiting for RecoveryRequest for a more deterministic UT
            backupOnRecoveryDueToFailedNodes = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            recoveryPayload = (ConsensusPayload)backupOnRecoveryDueToFailedNodes.Inventory;
            rrm = (RecoveryRequest)recoveryPayload.ConsensusMessage;
            rrm.Timestamp.Should().Be(defaultTimestamp);
            //Asserts            
            Console.WriteLine("\nAsserting PreparationPayloads count is 4...");
            mockContext.Object.PreparationPayloads.Count(p => p != null).Should().Be(4);
            Console.WriteLine($"\nAsserting CountFailed is 3...");
            mockContext.Object.CountFailed.Should().Be(3);

            // Simulating CN 4
            actorConsensus.Tell(GetPayloadAndModifyValidator(prepResponsePayload, 3));
            var onCommitPayload = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var commitPayload = (ConsensusPayload)onCommitPayload.Inventory;
            Commit cm = (Commit)commitPayload.ConsensusMessage;
            Console.WriteLine("\nAsserting PreparationPayloads count is 5...");
            mockContext.Object.PreparationPayloads.Count(p => p != null).Should().Be(5);
            Console.WriteLine("\nAsserting CountCommitted is 1...");
            mockContext.Object.CountCommitted.Should().Be(1);
            Console.WriteLine($"\nAsserting CountFailed is 2...");
            mockContext.Object.CountFailed.Should().Be(2);

            Console.WriteLine($"ORIGINAL BlockHash: {mockContext.Object.Block.Hash}");
            Console.WriteLine($"ORIGINAL Block NextConsensus: {mockContext.Object.Block.NextConsensus}");

            for (int i = 0; i < mockContext.Object.Validators.Length; i++)
                Console.WriteLine($"{mockContext.Object.Validators[i]}/{Contract.CreateSignatureContract(mockContext.Object.Validators[i]).ScriptHash}");
            mockContext.Object.Validators = new ECPoint[7]
                {
                    kp_array[0].PublicKey,
                    kp_array[1].PublicKey,
                    kp_array[2].PublicKey,
                    kp_array[3].PublicKey,
                    kp_array[4].PublicKey,
                    kp_array[5].PublicKey,
                    kp_array[6].PublicKey
                };
            Console.WriteLine($"Generated keypairs PKey:");
            for (int i = 0; i < mockContext.Object.Validators.Length; i++)
                Console.WriteLine($"{mockContext.Object.Validators[i]}/{Contract.CreateSignatureContract(mockContext.Object.Validators[i]).ScriptHash}");
            var updatedContract = Contract.CreateMultiSigContract(mockContext.Object.M, mockContext.Object.Validators);
            Console.WriteLine($"\nContract updated: {updatedContract.ScriptHash}");

            // ===============================================================
            mockContext.Object.Snapshot.Storages.Add(CreateStorageKeyForNativeNeo(14), new StorageItem()
            {
                Value = mockContext.Object.Validators.ToByteArray()
            });
            mockContext.Object.Snapshot.Commit();
            // ===============================================================

            // Forcing next consensus
            var originalBlockHashData = mockContext.Object.Block.GetHashData();
            mockContext.Object.Block.NextConsensus = updatedContract.ScriptHash;
            mockContext.Object.Block.Header.NextConsensus = updatedContract.ScriptHash;
            var originalBlockMerkleRoot = mockContext.Object.Block.MerkleRoot;
            Console.WriteLine($"\noriginalBlockMerkleRoot: {originalBlockMerkleRoot}");
            var updatedBlockHashData = mockContext.Object.Block.GetHashData();
            Console.WriteLine($"originalBlockHashData: {originalBlockHashData.ToScriptHash()}");
            Console.WriteLine($"updatedBlockHashData: {updatedBlockHashData.ToScriptHash()}");

            Console.WriteLine("\n\n==========================");
            Console.WriteLine("\nBasic commits Signatures verification");
            // Basic tests for understanding signatures and ensuring signatures of commits are correct on tests
            var cmPayloadTemp = GetCommitPayloadModifiedAndSignedCopy(commitPayload, 6, kp_array[6], updatedBlockHashData);
            Crypto.VerifySignature(originalBlockHashData, cm.Signature, mockContext.Object.Validators[0]).Should().BeFalse();
            Crypto.VerifySignature(updatedBlockHashData, cm.Signature, mockContext.Object.Validators[0]).Should().BeFalse();
            Crypto.VerifySignature(originalBlockHashData, ((Commit)cmPayloadTemp.ConsensusMessage).Signature, mockContext.Object.Validators[6]).Should().BeFalse();
            Crypto.VerifySignature(updatedBlockHashData, ((Commit)cmPayloadTemp.ConsensusMessage).Signature, mockContext.Object.Validators[6]).Should().BeTrue();
            Console.WriteLine("\n==========================");

            Console.WriteLine("\n==========================");
            Console.WriteLine("\nCN7 simulation time");
            actorConsensus.Tell(cmPayloadTemp);
            var tempPayloadToBlockAndWait = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var rmPayload = (ConsensusPayload)tempPayloadToBlockAndWait.Inventory;
            RecoveryMessage rmm = (RecoveryMessage)rmPayload.ConsensusMessage;
            Console.WriteLine("\nAsserting CountCommitted is 2...");
            mockContext.Object.CountCommitted.Should().Be(2);
            Console.WriteLine($"\nAsserting CountFailed is 1...");
            mockContext.Object.CountFailed.Should().Be(1);

            Console.WriteLine("\nCN6 simulation time");
            actorConsensus.Tell(GetCommitPayloadModifiedAndSignedCopy(commitPayload, 5, kp_array[5], updatedBlockHashData));
            tempPayloadToBlockAndWait = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            rmPayload = (ConsensusPayload)tempPayloadToBlockAndWait.Inventory;
            rmm = (RecoveryMessage)rmPayload.ConsensusMessage;
            Console.WriteLine("\nAsserting CountCommitted is 3...");
            mockContext.Object.CountCommitted.Should().Be(3);
            Console.WriteLine($"\nAsserting CountFailed is 0...");
            mockContext.Object.CountFailed.Should().Be(0);

            Console.WriteLine("\nCN5 simulation time");
            actorConsensus.Tell(GetCommitPayloadModifiedAndSignedCopy(commitPayload, 4, kp_array[4], updatedBlockHashData));
            tempPayloadToBlockAndWait = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            Console.WriteLine("\nAsserting CountCommitted is 4...");
            mockContext.Object.CountCommitted.Should().Be(4);

            // =============================================
            // Testing commit with wrong signature not valid
            // It will be invalid signature because we did not change ECPoint
            Console.WriteLine("\nCN4 simulation time. Wrong signature, KeyPair is not known");
            actorConsensus.Tell(GetPayloadAndModifyValidator(commitPayload, 3));
            Console.WriteLine("\nWaiting for recovery due to failed nodes... ");
            var backupOnRecoveryMessageAfterCommit = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            rmPayload = (ConsensusPayload)backupOnRecoveryMessageAfterCommit.Inventory;
            rmm = (RecoveryMessage)rmPayload.ConsensusMessage;
            Console.WriteLine("\nAsserting CountCommitted is 4 (Again)...");
            mockContext.Object.CountCommitted.Should().Be(4);
            Console.WriteLine("\nAsserting recovery message Preparation is 5...");
            rmm.PreparationMessages.Count().Should().Be(5);
            Console.WriteLine("\nAsserting recovery message CommitMessages is 4...");
            rmm.CommitMessages.Count().Should().Be(4);
            // =============================================

            Console.WriteLine($"\nForcing block {mockContext.Object.Block.GetHashData().ToScriptHash()} PrevHash to UInt256.Zero");
            // Another option would be to manipulate Blockchain.Singleton.GetSnapshot().Blocks.GetAndChange
            // We would need to get the PrevHash and change the NextConsensus field
            var oldPrevHash = mockContext.Object.Block.PrevHash;
            mockContext.Object.Block.PrevHash = UInt256.Zero;
            //Payload should also be forced, otherwise OnConsensus will not pass
            commitPayload.PrevHash = UInt256.Zero;
            Console.WriteLine($"\nNew Hash is {mockContext.Object.Block.GetHashData().ToScriptHash()}");
            Console.WriteLine($"\nForcing block VerificationScript to {updatedContract.Script.ToScriptHash()}");
            // The default behavior for BlockBase, when PrevHash = UInt256.Zero, is to use its own Witness
            mockContext.Object.Block.Witness = new Witness { };
            mockContext.Object.Block.Witness.VerificationScript = updatedContract.Script;
            Console.WriteLine($"\nUpdating BlockBase Witness scripthash to: {mockContext.Object.Block.Witness.ScriptHash}");
            Console.WriteLine($"\nNew Hash is {mockContext.Object.Block.GetHashData().ToScriptHash()}");

            Console.WriteLine("\nCN4 simulation time - Final needed signatures");
            actorConsensus.Tell(GetCommitPayloadModifiedAndSignedCopy(commitPayload, 3, kp_array[3], mockContext.Object.Block.GetHashData()));

            Console.WriteLine("\nWait for subscriber Local.Node Relay");
            var onBlockRelay = subscriber.ExpectMsg<LocalNode.Relay>();
            Console.WriteLine("\nAsserting time was Block...");
            var utBlock = (Block)onBlockRelay.Inventory;
            Console.WriteLine("\nAsserting CountCommitted is 5...");
            mockContext.Object.CountCommitted.Should().Be(5);

            Console.WriteLine($"\nAsserting block NextConsensus..{utBlock.NextConsensus}");
            utBlock.NextConsensus.Should().Be(updatedContract.ScriptHash);
            Console.WriteLine("\n==========================");

            // =============================================
            Console.WriteLine("\nRecovery simulation...");
            mockContext.Object.CommitPayloads = new ConsensusPayload[mockContext.Object.Validators.Length];
            // avoiding the BlockSent flag
            mockContext.Object.Block.Transactions = null;
            // ensuring same hash as snapshot
            mockContext.Object.Block.PrevHash = oldPrevHash;

            Console.WriteLine("\nAsserting CountCommitted is 0...");
            mockContext.Object.CountCommitted.Should().Be(0);
            Console.WriteLine($"\nAsserting CountFailed is 0...");
            mockContext.Object.CountFailed.Should().Be(0);
            Console.WriteLine($"\nModifying CountFailed and asserting 7...");
            // This will ensure a non-deterministic behavior after last recovery
            mockContext.Object.LastSeenMessage = new int[] { -1, -1, -1, -1, -1, -1, -1 };
            mockContext.Object.CountFailed.Should().Be(7);

            actorConsensus.Tell(rmPayload);

            Console.WriteLine("\nWaiting for RecoveryRequest before final asserts...");
            var onRecoveryRequestAfterRecovery = subscriber.ExpectMsg<LocalNode.SendDirectly>();
            var rrPayload = (ConsensusPayload)onRecoveryRequestAfterRecovery.Inventory;
            var rrMessage = (RecoveryRequest)rrPayload.ConsensusMessage;

            // It should be 3 because the commit generated by the default wallet is still invalid
            Console.WriteLine("\nAsserting CountCommitted is 3 (after recovery)...");
            mockContext.Object.CountCommitted.Should().Be(3);
            // =============================================

            // =============================================
            // ============================================================================
            //                      finalize ConsensusService actor
            // ============================================================================
            Console.WriteLine("Returning states.");
            // Updating context.Snapshot with the one that was committed
            Console.WriteLine("mockContext Reset for returning Blockchain.Singleton snapshot to original state.");
            mockContext.Object.Reset(0);
            mockContext.Object.Snapshot.Storages.Delete(CreateStorageKeyForNativeNeo(14));
            mockContext.Object.Snapshot.Commit();

            Console.WriteLine("mockContext Reset.");
            mockContext.Object.Reset(0);
            Console.WriteLine("TimeProvider Reset.");
            TimeProvider.ResetToDefault();

            Console.WriteLine("Finalizing consensus service actor.");
            Sys.Stop(actorConsensus);
            Console.WriteLine("Actor actorConsensus Stopped.\n");
        }
Пример #25
0
        public void CreateForumWithEmptyName()
        {
            NForum.CQS.Commands.Forums.CreateForumCommand create = new CQS.Commands.Forums.CreateForumCommand {
                CategoryId = 765.ToString(),
                Name       = String.Empty
            };

            NForum.CQS.Validators.Forums.CreateForumValidator validator = new CQS.Validators.Forums.CreateForumValidator(TestUtils.GetInt32IdValidator());

            ValidationResult result = validator.Validate(create);

            result.IsValid.Should().Be(false, "An empty name is not allowed");

            create.Name = "    ";
            result      = validator.Validate(create);
            result.IsValid.Should().Be(false, "An empty name is not allowed");

            create.Name = "\t";
            result      = validator.Validate(create);
            result.IsValid.Should().Be(false, "An empty name is not allowed");

            create.Name = null;
            result      = validator.Validate(create);
            result.IsValid.Should().Be(false, "An empty name is not allowed");
        }
Пример #26
0
        public void TestSerializeAndDeserializeRecoveryMessageWithChangeViewsAndNoPrepareRequest()
        {
            var msg = new RecoveryMessage
            {
                ChangeViewMessages = new Dictionary<int, RecoveryMessage.ChangeViewPayloadCompact>()
                {
                    {
                        0,
                        new RecoveryMessage.ChangeViewPayloadCompact
                        {
                            ValidatorIndex = 0,
                            OriginalViewNumber = 9,
                            Timestamp = 6,
                            InvocationScript = new[] { (byte)'A' }
                        }
                    },
                    {
                        1,
                        new RecoveryMessage.ChangeViewPayloadCompact
                        {
                            ValidatorIndex = 1,
                            OriginalViewNumber = 7,
                            Timestamp = 5,
                            InvocationScript = new[] { (byte)'B' }
                        }
                    },
                    {
                        3,
                        new RecoveryMessage.ChangeViewPayloadCompact
                        {
                            ValidatorIndex = 3,
                            OriginalViewNumber = 5,
                            Timestamp = 3,
                            InvocationScript = new[] { (byte)'C' }
                        }
                    },
                    {
                        6,
                        new RecoveryMessage.ChangeViewPayloadCompact
                        {
                            ValidatorIndex = 6,
                            OriginalViewNumber = 2,
                            Timestamp = 1,
                            InvocationScript = new[] { (byte)'D' }
                        }
                    }
                },
                PreparationHash = new UInt256(Crypto.Hash256(new[] { (byte)'a' })),
                PreparationMessages = new Dictionary<int, RecoveryMessage.PreparationPayloadCompact>()
                {
                    {
                        0,
                        new RecoveryMessage.PreparationPayloadCompact
                        {
                            ValidatorIndex = 0,
                            InvocationScript = new[] { (byte)'t', (byte)'e' }
                        }
                    },
                    {
                        3,
                        new RecoveryMessage.PreparationPayloadCompact
                        {
                            ValidatorIndex = 3,
                            InvocationScript = new[] { (byte)'1', (byte)'2' }
                        }
                    },
                    {
                        6,
                        new RecoveryMessage.PreparationPayloadCompact
                        {
                            ValidatorIndex = 6,
                            InvocationScript = new[] { (byte)'3', (byte)'!' }
                        }
                    }
                },
                CommitMessages = new Dictionary<int, RecoveryMessage.CommitPayloadCompact>()
            };

            // msg.TransactionHashes = null;
            // msg.Nonce = 0;
            // msg.NextConsensus = null;
            // msg.MinerTransaction = (MinerTransaction) null;
            msg.PrepareRequestMessage.Should().Be(null);

            var copiedMsg = TestUtils.CopyMsgBySerialization(msg, new RecoveryMessage()); ;

            copiedMsg.ChangeViewMessages.Should().BeEquivalentTo(msg.ChangeViewMessages);
            copiedMsg.PreparationHash.Should().Be(msg.PreparationHash);
            copiedMsg.PreparationMessages.Should().BeEquivalentTo(msg.PreparationMessages);
            copiedMsg.CommitMessages.Count.Should().Be(0);
        }
Пример #27
0
        public void CreateForumWithNameAndParentId()
        {
            NForum.CQS.Commands.Forums.CreateForumCommand create = new NForum.CQS.Commands.Forums.CreateForumCommand {
                Name          = "Just anything",
                ParentForumId = 23456.ToString()
            };

            NForum.CQS.Validators.Forums.CreateForumValidator validator = new CQS.Validators.Forums.CreateForumValidator(TestUtils.GetInt32IdValidator());

            ValidationResult result = validator.Validate(create);

            result.IsValid.Should().Be(true, "A name and parent forum or category id was provided");

            create.ParentForumId = String.Empty;
            create.CategoryId    = 34567.ToString();

            result = validator.Validate(create);
            result.IsValid.Should().Be(true, "A name and parent forum or category id was provided");
        }
Пример #28
0
        public void TestSerializeAndDeserializeRecoveryMessageWithoutChangeViewsWithCommits()
        {
            Transaction[] txs = new Transaction[5];
            for (int i = 0; i < txs.Length; i++)
                txs[i] = TestUtils.CreateRandomHashTransaction();
            var msg = new RecoveryMessage
            {
                ChangeViewMessages = new Dictionary<int, RecoveryMessage.ChangeViewPayloadCompact>(),
                PrepareRequestMessage = new PrepareRequest
                {
                    TransactionHashes = txs.Select(p => p.Hash).ToArray()
                },
                PreparationMessages = new Dictionary<int, RecoveryMessage.PreparationPayloadCompact>()
                {
                    {
                        0,
                        new RecoveryMessage.PreparationPayloadCompact
                        {
                            ValidatorIndex = 0,
                            InvocationScript = new[] { (byte)'t', (byte)'e' }
                        }
                    },
                    {
                        1,
                        new RecoveryMessage.PreparationPayloadCompact
                        {
                            ValidatorIndex = 1,
                            InvocationScript = new[] { (byte)'s', (byte)'t' }
                        }
                    },
                    {
                        3,
                        new RecoveryMessage.PreparationPayloadCompact
                        {
                            ValidatorIndex = 3,
                            InvocationScript = new[] { (byte)'1', (byte)'2' }
                        }
                    },
                    {
                        6,
                        new RecoveryMessage.PreparationPayloadCompact
                        {
                            ValidatorIndex = 6,
                            InvocationScript = new[] { (byte)'3', (byte)'!' }
                        }
                    }
                },
                CommitMessages = new Dictionary<int, RecoveryMessage.CommitPayloadCompact>
                {
                    {
                        1,
                        new RecoveryMessage.CommitPayloadCompact
                        {
                            ValidatorIndex = 1,
                            Signature = new byte[64] { (byte)'1', (byte)'2', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
                            InvocationScript = new[] { (byte)'1', (byte)'2' }
                        }
                    },
                    {
                        6,
                        new RecoveryMessage.CommitPayloadCompact
                        {
                            ValidatorIndex = 6,
                            Signature = new byte[64] { (byte)'3', (byte)'D', (byte)'R', (byte)'I', (byte)'N', (byte)'K', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
                            InvocationScript = new[] { (byte)'6', (byte)'7' }
                        }
                    }
                }
            };

            var copiedMsg = TestUtils.CopyMsgBySerialization(msg, new RecoveryMessage()); ;

            copiedMsg.ChangeViewMessages.Count.Should().Be(0);
            copiedMsg.PrepareRequestMessage.Should().BeEquivalentTo(msg.PrepareRequestMessage);
            copiedMsg.PreparationHash.Should().Be(null);
            copiedMsg.PreparationMessages.Should().BeEquivalentTo(msg.PreparationMessages);
            copiedMsg.CommitMessages.Should().BeEquivalentTo(msg.CommitMessages);
        }
Пример #29
0
        public void UpdateForumWithNameAndId()
        {
            NForum.CQS.Commands.Forums.UpdateForumCommand update = new CQS.Commands.Forums.UpdateForumCommand {
                Id   = 634634.ToString(),
                Name = "meh"
            };

            NForum.CQS.Validators.Forums.UpdateForumValidator validator = new NForum.CQS.Validators.Forums.UpdateForumValidator(TestUtils.GetInt32IdValidator());

            ValidationResult result = validator.Validate(update);

            result.IsValid.Should().Be(true, "A name and id was provide");
        }
        [WorkItem(126)] // Exclude secrets from log data: http://jira.sonarsource.com/browse/SONARMSBRU-126
        public void ProcRunner_DoNotLogSensitiveData()
        {
            // Arrange
            string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
            // Create a dummy exe that will produce a log file showing any input args
            string exeName = DummyExeHelper.CreateDummyPostProcessor(testDir, 0);

            TestLogger logger = new TestLogger();

            // Public args - should appear in the log
            string[] publicArgs = new string[]
            {
                "public1",
                "public2",
                "/d:sonar.projectKey=my.key"
            };

            string[] sensitiveArgs = new string[] {
                // Public args - should appear in the log
                "public1", "public2", "/dmy.key=value",

                // Sensitive args - should not appear in the log
                "/d:sonar.password=secret data password",
                "/d:sonar.login=secret data login",
                "/d:sonar.jdbc.password=secret data db password",
                "/d:sonar.jdbc.username=secret data db user name",

                // Sensitive args - different cases -> exclude to be on the safe side
                "/d:SONAR.jdbc.password=secret data db password upper",
                "/d:sonar.PASSWORD=secret data password upper",

                // Sensitive args - parameter format is slightly incorrect -> exclude to be on the safe side
                "/dsonar.login =secret data key typo",
                "sonar.password=secret data password typo"
            };

            string[] allArgs = sensitiveArgs.Union(publicArgs).ToArray();

            ProcessRunnerArguments runnerArgs = new ProcessRunnerArguments(exeName, false, logger)
            {
                CmdLineArgs = allArgs
            };
            ProcessRunner runner = new ProcessRunner();

            // Act
            bool success = runner.Execute(runnerArgs);

            // Assert
            Assert.IsTrue(success, "Expecting the process to have succeeded");
            Assert.AreEqual(0, runner.ExitCode, "Unexpected exit code");

            // Check public arguments are logged but private ones are not
            foreach(string arg in publicArgs)
            {
                logger.AssertSingleDebugMessageExists(arg);
            }

            logger.AssertSingleDebugMessageExists(SonarQube.Common.Resources.MSG_CmdLine_SensitiveCmdLineArgsAlternativeText);
            AssertTextDoesNotAppearInLog("secret", logger);

            // Check that the public and private arguments are passed to the child process
            string exeLogFile = DummyExeHelper.AssertDummyPostProcLogExists(testDir, this.TestContext);
            DummyExeHelper.AssertExpectedLogContents(exeLogFile, allArgs);
        }
Пример #31
0
        public void DeleteForumWithId()
        {
            NForum.CQS.Commands.Forums.DeleteForumCommand delete = new CQS.Commands.Forums.DeleteForumCommand {
                Id = 76554.ToString()
            };

            NForum.CQS.Validators.Forums.DeleteForumValidator validator = new CQS.Validators.Forums.DeleteForumValidator(TestUtils.GetInt32IdValidator());

            ValidationResult result = validator.Validate(delete);

            result.IsValid.Should().Be(true, "An id was provided");
        }