Exemple #1
0
 public static object ShouldNotEqual(this object actual, object expected)
 {
     Assert.AreNotEqual(expected, actual);
     return(expected);
 }
 private static void AssertProcessExitsWithFailure(ProcessResult result)
 {
     Assert.AreNotEqual(ProcessResult.SUCCESSFUL_EXIT_CODE, result.ExitCode);
     Assert.IsTrue(result.Failed, "process should return an error");
 }
        public void Test0050()
        {
            #region テストデータ準備

            var testEntityBeforeUpdate = TestUtilLib.GenarateRandomTodoTask();
            var testEntityOfUpdate     = TestUtilLib.GenarateRandomTodoTask();
            var testEntityOfAdd1       = TestUtilLib.GenarateRandomTodoTask();
            var testEntityOfAdd2       = new TodoTask();
            testEntityOfUpdate.TodoTaskId = testEntityBeforeUpdate.TodoTaskId;
            testEntityOfUpdate.DueDate    = testEntityBeforeUpdate.DueDate.Value.AddMinutes(1);

            using (var context = new EfDbContext())
            {
                context.Add(testEntityBeforeUpdate);
                context.SaveChanges();
            }
            using (var context = new EfDbContext()) Assert.AreEqual(1, context.TodoTasks.Count());

            #endregion

            TodoTask dbEntity;
            Assert.AreEqual(1, DalTodoTask.Upsert(testEntityOfUpdate));

            #region データを取得し、結果を確認(全て一致するはず(レコード登録日時、レコード更新日時 は比較除外))

            using (var context = new EfDbContext()) dbEntity = context.TodoTasks.Find(testEntityOfUpdate.TodoTaskId);

            foreach (var property in testEntityOfUpdate.GetType().GetProperties())
            {
                switch (property.Name)
                {
                case nameof(testEntityOfUpdate.TodoTaskId):
                    Assert.AreEqual(property.GetValue(testEntityBeforeUpdate), property.GetValue(dbEntity));
                    Assert.AreEqual(property.GetValue(testEntityOfUpdate), property.GetValue(dbEntity));
                    break;

                case nameof(testEntityOfUpdate.CreateDateTime):
                case nameof(testEntityOfUpdate.UpdateDateTime):
                    break;

                default:
                    Assert.AreNotEqual(property.GetValue(testEntityBeforeUpdate), property.GetValue(dbEntity));
                    Assert.AreEqual(property.GetValue(testEntityOfUpdate), property.GetValue(dbEntity));
                    break;
                }
            }

            #endregion

            Assert.AreEqual(1, DalTodoTask.Upsert(testEntityOfAdd1));

            #region データを取得し、結果を確認(全て一致するはず(レコード登録日時、レコード更新日時 は比較除外))

            using (var context = new EfDbContext()) dbEntity = context.TodoTasks.Find(testEntityOfAdd1.TodoTaskId);

            foreach (var property in testEntityOfAdd1.GetType().GetProperties())
            {
                switch (property.Name)
                {
                case nameof(testEntityOfAdd1.CreateDateTime):
                case nameof(testEntityOfAdd1.UpdateDateTime):
                    Assert.AreNotEqual(property.GetValue(testEntityOfAdd1), property.GetValue(dbEntity));
                    break;

                default:
                    Assert.AreEqual(property.GetValue(testEntityOfAdd1), property.GetValue(dbEntity));
                    break;
                }
            }

            #endregion

            Assert.AreEqual(1, DalTodoTask.Upsert(testEntityOfAdd2));

            #region データを取得し、結果を確認(全て一致するはず(レコード登録日時、レコード更新日時 は比較除外))

            using (var context = new EfDbContext()) dbEntity = context.TodoTasks.Find(testEntityOfAdd2.TodoTaskId);

            foreach (var property in testEntityOfAdd2.GetType().GetProperties())
            {
                switch (property.Name)
                {
                case nameof(testEntityOfAdd2.CreateDateTime):
                case nameof(testEntityOfAdd2.UpdateDateTime):
                    Assert.AreNotEqual(property.GetValue(testEntityOfAdd2), property.GetValue(dbEntity));
                    break;

                default:
                    Assert.AreEqual(property.GetValue(testEntityOfAdd2), property.GetValue(dbEntity));
                    break;
                }
            }

            #endregion
        }
        public async Task CloudFileCopyTestTask()
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

                CloudFile source = share.GetRootDirectoryReference().GetFileReference("source");

                string data = "String data";
                UploadTextTask(source, data, Encoding.UTF8);

                source.Metadata["Test"] = "value";
                await source.SetMetadataAsync();

                CloudFile copy   = share.GetRootDirectoryReference().GetFileReference("copy");
                string    copyId = await copy.StartCopyAsync(TestHelper.Defiddler(source));

                WaitForCopyTask(copy);
                Assert.AreEqual(CopyStatus.Success, copy.CopyState.Status);
                Assert.AreEqual(source.Uri.AbsolutePath, copy.CopyState.Source.AbsolutePath);
                Assert.AreEqual(data.Length, copy.CopyState.TotalBytes);
                Assert.AreEqual(data.Length, copy.CopyState.BytesCopied);
                Assert.AreEqual(copyId, copy.CopyState.CopyId);
                Assert.IsTrue(copy.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                TestHelper.ExpectedExceptionTask(
                    copy.AbortCopyAsync(copyId),
                    "Aborting a copy operation after completion should fail",
                    HttpStatusCode.Conflict,
                    "NoPendingCopyOperation");

                await source.FetchAttributesAsync();

                Assert.IsNotNull(copy.Properties.ETag);
                Assert.AreNotEqual(source.Properties.ETag, copy.Properties.ETag);
                Assert.IsTrue(copy.Properties.LastModified > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                string copyData = DownloadTextTask(copy, Encoding.UTF8);
                Assert.AreEqual(data, copyData, "Data inside copy of file not similar");

                await copy.FetchAttributesAsync();

                FileProperties prop1 = copy.Properties;
                FileProperties prop2 = source.Properties;

                Assert.AreEqual(prop1.CacheControl, prop2.CacheControl);
                Assert.AreEqual(prop1.ContentEncoding, prop2.ContentEncoding);
                Assert.AreEqual(prop1.ContentLanguage, prop2.ContentLanguage);
                Assert.AreEqual(prop1.ContentMD5, prop2.ContentMD5);
                Assert.AreEqual(prop1.ContentType, prop2.ContentType);

                Assert.AreEqual("value", copy.Metadata["Test"], false, "Copied metadata not same");

                await copy.DeleteAsync();
            }
            finally
            {
                await share.DeleteAsync();
            }
        }
Exemple #5
0
        public void TestLoggingSystemStats()
        {
            testName = "TestLoggingSystemStats";
            testHome = testFixtureHome + "/" + testName;
            string logDir = "./";

            Configuration.ClearDir(testHome);
            Directory.CreateDirectory(testHome + "/" + logDir);

            DatabaseEnvironmentConfig cfg =
                new DatabaseEnvironmentConfig();

            cfg.Create                   = true;
            cfg.UseTxns                  = true;
            cfg.AutoCommit               = true;
            cfg.UseLocking               = true;
            cfg.UseMPool                 = true;
            cfg.UseLogging               = true;
            cfg.MPoolSystemCfg           = new MPoolConfig();
            cfg.MPoolSystemCfg.CacheSize = new CacheInfo(0, 1048576, 1);

            cfg.LogSystemCfg              = new LogConfig();
            cfg.LogSystemCfg.AutoRemove   = false;
            cfg.LogSystemCfg.BufferSize   = 10240;
            cfg.LogSystemCfg.Dir          = logDir;
            cfg.LogSystemCfg.FileMode     = 755;
            cfg.LogSystemCfg.ForceSync    = true;
            cfg.LogSystemCfg.InMemory     = false;
            cfg.LogSystemCfg.MaxFileSize  = 1048576;
            cfg.LogSystemCfg.NoBuffer     = false;
            cfg.LogSystemCfg.RegionSize   = 204800;
            cfg.LogSystemCfg.ZeroOnCreate = true;

            DatabaseEnvironment env = DatabaseEnvironment.Open(testHome, cfg);

            LogStats stats = env.LoggingSystemStats();

            env.PrintLoggingSystemStats();
            Assert.AreEqual(10240, stats.BufferSize);
            Assert.AreEqual(1, stats.CurrentFile);
            Assert.AreNotEqual(0, stats.CurrentOffset);
            Assert.AreEqual(1048576, stats.FileSize);
            Assert.AreNotEqual(0, stats.MagicNumber);
            Assert.AreNotEqual(0, stats.PermissionsMode);
            Assert.AreEqual(1, stats.Records);
            Assert.AreNotEqual(0, stats.RegionLockNoWait);
            Assert.LessOrEqual(204800, stats.RegionSize);
            Assert.AreNotEqual(0, stats.Version);

            Transaction         openTxn  = env.BeginTransaction();
            BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig();

            dbConfig.Creation = CreatePolicy.IF_NEEDED;
            dbConfig.Env      = env;
            BTreeDatabase db = BTreeDatabase.Open(testName + ".db", dbConfig, openTxn);

            openTxn.Commit();

            Transaction writeTxn = env.BeginTransaction();

            byte[] byteArr = new byte[1024];
            for (int i = 0; i < 1000; i++)
            {
                db.Put(new DatabaseEntry(BitConverter.GetBytes(i)),
                       new DatabaseEntry(byteArr), writeTxn);
            }
            writeTxn.Commit();

            stats = env.LoggingSystemStats();
            Assert.AreNotEqual(0, stats.Bytes);
            Assert.AreNotEqual(0, stats.BytesSinceCheckpoint);
            Assert.AreNotEqual(0, stats.DiskFileNumber);
            Assert.AreNotEqual(0, stats.DiskOffset);
            Assert.AreNotEqual(0, stats.MaxCommitsPerFlush);
            Assert.AreNotEqual(0, stats.MBytes);
            Assert.AreNotEqual(0, stats.MBytesSinceCheckpoint);
            Assert.AreNotEqual(0, stats.MinCommitsPerFlush);
            Assert.AreNotEqual(0, stats.OverflowWrites);
            Assert.AreNotEqual(0, stats.Syncs);
            Assert.AreNotEqual(0, stats.Writes);
            Assert.AreEqual(0, stats.Reads);
            Assert.AreEqual(0, stats.RegionLockWait);

            stats = env.LoggingSystemStats(true);
            stats = env.LoggingSystemStats();
            Assert.AreEqual(0, stats.Bytes);
            Assert.AreEqual(0, stats.BytesSinceCheckpoint);
            Assert.AreEqual(0, stats.MaxCommitsPerFlush);
            Assert.AreEqual(0, stats.MBytes);
            Assert.AreEqual(0, stats.MBytesSinceCheckpoint);
            Assert.AreEqual(0, stats.MinCommitsPerFlush);
            Assert.AreEqual(0, stats.OverflowWrites);
            Assert.AreEqual(0, stats.Syncs);
            Assert.AreEqual(0, stats.Writes);
            Assert.AreEqual(0, stats.Reads);

            env.PrintLoggingSystemStats(true, true);

            db.Close();
            env.Close();
        }
Exemple #6
0
        public async Task Bug57840()
        {
            var templatingService            = new TemplatingService();
            var mutliplatformLibraryCategory = templatingService.GetProjectTemplateCategories().Single(c => c.Id == "multiplat")
                                               .Categories.Single(c => c.Id == "library")
                                               .Categories.Single(c => c.Id == "general");
            var pclTemplate      = mutliplatformLibraryCategory.Templates.Single(t => t.GroupId == "md-project-portable-library").GetTemplate("C#");
            var standardTemplate = mutliplatformLibraryCategory.Templates.Single(t => t.GroupId == "Microsoft.Common.Library").GetTemplate("C#");

            var tempDirectory = Util.CreateTmpDir("Bug57840Test");
            var result        = await templatingService.ProcessTemplate(pclTemplate, new Ide.Projects.NewProjectConfiguration()
            {
                CreateSolution = true,
                Location       = tempDirectory,
                SolutionName   = "Bug57840Test",
                ProjectName    = "Bug57840PclTestProject",
                CreateProjectDirectoryInsideSolutionDirectory = false
            }, null);

            var solution = result.WorkspaceItems.OfType <Solution> ().Single();

            await solution.SaveAsync(Util.GetMonitor());

            var project = solution.GetAllProjects().Single();

            project.Policies.Set <TextStylePolicy> (new TextStylePolicy(1, 1, 1, true, true, true, EolMarker.Mac), "text/x-csharp");

            var file = project.Files.Single(f => f.FilePath.FileName == "MyClass.cs").FilePath;
            var fileContentBeforeFormat = await TextFileUtility.ReadAllTextAsync(file);

            await FormatFile(project, file);

            var fileContentAfterFormat = await TextFileUtility.ReadAllTextAsync(file);

            Assert.AreNotEqual(fileContentBeforeFormat.Text, fileContentAfterFormat.Text);             //Make sure our weird formatting applied

            solution.Policies.Set <TextStylePolicy> (new TextStylePolicy(3, 3, 3, true, true, true, EolMarker.Mac), "text/x-csharp");

            var result2 = await templatingService.ProcessTemplate(standardTemplate, new Ide.Projects.NewProjectConfiguration()
            {
                CreateSolution = false,
                Location       = solution.BaseDirectory,
                ProjectName    = "Bug57840StandardTestProject",
                CreateProjectDirectoryInsideSolutionDirectory = false
            }, solution.RootFolder);

            await solution.SaveAsync(Util.GetMonitor());

            var fileContentAfterSecondProject = await TextFileUtility.ReadAllTextAsync(file);

            Assert.AreEqual(fileContentAfterSecondProject.Text, fileContentAfterFormat.Text);             //Make sure our weird formatting is preserved
            var standardProject          = result2.WorkspaceItems.OfType <DotNetProject> ().Single();
            var class1File               = standardProject.Files.Single(f => f.FilePath.FileName == "Class1.cs").FilePath;
            var fileContentAfterCreation = await TextFileUtility.ReadAllTextAsync(class1File);

            standardProject.Policies.Set <TextStylePolicy> (new TextStylePolicy(3, 3, 3, true, true, true, EolMarker.Mac), "text/x-csharp");
            await FormatFile(standardProject, class1File);

            var fileContentAfterForceFormatting = await TextFileUtility.ReadAllTextAsync(class1File);

            Assert.AreEqual(fileContentAfterForceFormatting.Text, fileContentAfterCreation.Text,
                            "We expect them to be same because we placed same formatting policy on solution before creataion as after creation on project when we manually formatted.");
        }
        public void CloudFileCopyTestAPM()
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                share.Create();

                CloudFile source = share.GetRootDirectoryReference().GetFileReference("source");

                string data = "String data";
                UploadText(source, data, Encoding.UTF8);

                source.Metadata["Test"] = "value";
                source.SetMetadata();

                CloudFile copy = share.GetRootDirectoryReference().GetFileReference("copy");
                using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                {
                    IAsyncResult result = copy.BeginStartCopy(TestHelper.Defiddler(source),
                                                              ar => waitHandle.Set(),
                                                              null);
                    waitHandle.WaitOne();
                    string copyId = copy.EndStartCopy(result);
                    WaitForCopy(copy);
                    Assert.AreEqual(CopyStatus.Success, copy.CopyState.Status);
                    Assert.AreEqual(source.Uri.AbsolutePath, copy.CopyState.Source.AbsolutePath);
                    Assert.AreEqual(data.Length, copy.CopyState.TotalBytes);
                    Assert.AreEqual(data.Length, copy.CopyState.BytesCopied);
                    Assert.AreEqual(copyId, copy.CopyState.CopyId);
                    Assert.IsTrue(copy.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                    result = copy.BeginAbortCopy(copyId,
                                                 ar => waitHandle.Set(),
                                                 null);
                    waitHandle.WaitOne();
                    TestHelper.ExpectedException(
                        () => copy.EndAbortCopy(result),
                        "Aborting a copy operation after completion should fail",
                        HttpStatusCode.Conflict,
                        "NoPendingCopyOperation");
                }

                source.FetchAttributes();
                Assert.IsNotNull(copy.Properties.ETag);
                Assert.AreNotEqual(source.Properties.ETag, copy.Properties.ETag);
                Assert.IsTrue(copy.Properties.LastModified > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                string copyData = DownloadText(copy, Encoding.UTF8);
                Assert.AreEqual(data, copyData, "Data inside copy of file not similar");

                copy.FetchAttributes();
                FileProperties prop1 = copy.Properties;
                FileProperties prop2 = source.Properties;

                Assert.AreEqual(prop1.CacheControl, prop2.CacheControl);
                Assert.AreEqual(prop1.ContentEncoding, prop2.ContentEncoding);
                Assert.AreEqual(prop1.ContentDisposition, prop2.ContentDisposition);
                Assert.AreEqual(prop1.ContentLanguage, prop2.ContentLanguage);
                Assert.AreEqual(prop1.ContentMD5, prop2.ContentMD5);
                Assert.AreEqual(prop1.ContentType, prop2.ContentType);

                Assert.AreEqual("value", copy.Metadata["Test"], false, "Copied metadata not same");

                copy.Delete();
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
Exemple #8
0
        public void TestWordConstructorFalse()
        {
            Word word = new Word("fiets");

            Assert.AreNotEqual("fsets", word.word);
        }
        public void ComputeMarginProperlyAsSecurityPriceFluctuates()
        {
            const decimal leverage = 1m;
            const int quantity = (int) (1000*leverage);
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(securities);
            var orderProcessor = new OrderProcessor();
            transactions.SetOrderProcessor(orderProcessor);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            portfolio.CashBook["USD"].SetAmount(quantity);

            var config = CreateTradeBarDataConfig(SecurityType.Equity, Symbols.AAPL);
            securities.Add(new Security(SecurityExchangeHours, config, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));
            var security = securities[Symbols.AAPL];
            security.SetLeverage(leverage);

            var time = DateTime.Now;
            const decimal buyPrice = 1m;
            security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, buyPrice, buyPrice, buyPrice, buyPrice, 1));

            var order = new MarketOrder(Symbols.AAPL, quantity, time) {Price = buyPrice};
            var fill = new OrderEvent(order, DateTime.UtcNow, 0) { FillPrice = buyPrice, FillQuantity = quantity };
            orderProcessor.AddOrder(order);
            var request = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, order.Quantity, 0, 0, order.Time, null);
            request.SetOrderId(0);
            orderProcessor.AddTicket(new OrderTicket(null, request));
            Assert.AreEqual(portfolio.CashBook["USD"].Amount, fill.FillPrice*fill.FillQuantity);

            portfolio.ProcessFill(fill);

            Assert.AreEqual(0, portfolio.MarginRemaining);
            Assert.AreEqual(quantity, portfolio.TotalMarginUsed);
            Assert.AreEqual(quantity, portfolio.TotalPortfolioValue);

            // we shouldn't be able to place a trader
            var newOrder = new MarketOrder(Symbols.AAPL, 1, time.AddSeconds(1)) {Price = buyPrice};
            bool sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder);
            Assert.IsFalse(sufficientCapital);

            // now the stock doubles, so we should have margin remaining

            time = time.AddDays(1);
            const decimal highPrice = buyPrice * 2;
            security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, highPrice, highPrice, highPrice, highPrice, 1));

            Assert.AreEqual(quantity, portfolio.MarginRemaining);
            Assert.AreEqual(quantity, portfolio.TotalMarginUsed);
            Assert.AreEqual(quantity * 2, portfolio.TotalPortfolioValue);

            // we shouldn't be able to place a trader
            var anotherOrder = new MarketOrder(Symbols.AAPL, 1, time.AddSeconds(1)) { Price = highPrice };
            sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, anotherOrder);
            Assert.IsTrue(sufficientCapital);

            // now the stock plummets, so we should have negative margin remaining

            time = time.AddDays(1);
            const decimal lowPrice = buyPrice/2;
            security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, lowPrice, lowPrice, lowPrice, lowPrice, 1));

            Assert.AreEqual(-quantity/2m, portfolio.MarginRemaining);
            Assert.AreEqual(quantity, portfolio.TotalMarginUsed);
            Assert.AreEqual(quantity/2m, portfolio.TotalPortfolioValue);


            // this would not cause a margin call due to leverage = 1
            bool issueMarginCallWarning;
            var marginCallOrders = portfolio.ScanForMarginCall(out issueMarginCallWarning);
            Assert.AreEqual(0, marginCallOrders.Count);

            // now change the leverage and buy more and we'll get a margin call
            security.SetLeverage(leverage * 2);

            order = new MarketOrder(Symbols.AAPL, quantity, time) { Price = buyPrice };
            fill = new OrderEvent(order, DateTime.UtcNow, 0) { FillPrice = buyPrice, FillQuantity = quantity };

            portfolio.ProcessFill(fill);

            Assert.AreEqual(0, portfolio.TotalPortfolioValue);

            marginCallOrders = portfolio.ScanForMarginCall(out issueMarginCallWarning);
            Assert.AreNotEqual(0, marginCallOrders.Count);
            Assert.AreEqual(-security.Holdings.Quantity, marginCallOrders[0].Quantity); // we bought twice
            Assert.GreaterOrEqual(-portfolio.MarginRemaining, security.Price * marginCallOrders[0].Quantity);
        }
Exemple #10
0
        private async Task TestMultipleBanTimespansAsync(bool resetFailedLogin)
        {
            string config = await service.ReadConfigAsync();

            string newConfig = IPBanConfig.ChangeConfigAppSetting(config, "BanTime", "00:00:01:00,00:00:02:00,00:00:03:00");

            newConfig = IPBanConfig.ChangeConfigAppSetting(newConfig, "ResetFailedLoginCountForUnbannedIPAddresses", resetFailedLogin.ToString());
            await service.WriteConfigAsync(newConfig);

            try
            {
                await service.RunCycle();

                Assert.AreEqual(3, service.Config.BanTimes.Length);
                Assert.AreEqual(resetFailedLogin, service.Config.ResetFailedLoginCountForUnbannedIPAddresses);
                for (int i = 1; i <= 3; i++)
                {
                    Assert.AreEqual(TimeSpan.FromMinutes(i), service.Config.BanTimes[i - 1]);
                }

                for (int i = 0; i < 4; i++)
                {
                    // forget all the bans, but they should still be in the database due to the multiple timespans as failed logins
                    IPBanService.UtcNow += TimeSpan.FromDays(14.0);
                    await service.RunCycle();

                    if (i < 3)
                    {
                        if (i > 0)
                        {
                            AssertIPAddressesAreNotBanned(true, true);
                        }

                        AddFailedLogins((i == 0 ? -1 : 1));

                        if (resetFailedLogin)
                        {
                            if (i > 0)
                            {
                                // after one fail login, should not be banned
                                AssertIPAddressesAreNotBanned(true, true);
                            }

                            // add more failed logins
                            AddFailedLogins();

                            // now they should be banned, fail login counts are reset upon ban
                            AssertIPAddressesAreBanned(0, 0);
                        }
                        else
                        {
                            // should have gotten back in with just a single failed login
                            AssertIPAddressesAreBanned(info1.Count + i, info2.Count + i);
                        }

                        Assert.IsTrue(service.DB.TryGetIPAddress(ip1, out IPBanDB.IPAddressEntry e1));
                        Assert.IsTrue(service.DB.TryGetIPAddress(ip2, out IPBanDB.IPAddressEntry e2));

                        // i == 3 means wrap around from 3 minutes back to 1 minute
                        TimeSpan expectedBanDuration = (i < 3 ? expectedBanDuration = TimeSpan.FromMinutes(i + 1) : TimeSpan.FromMinutes(1.0));
                        Assert.AreEqual(expectedBanDuration, e1.BanEndDate - e1.BanStartDate);
                        Assert.AreEqual(expectedBanDuration, e2.BanEndDate - e2.BanStartDate);
                        if (resetFailedLogin)
                        {
                            Assert.AreEqual(0, e1.FailedLoginCount);
                            Assert.AreEqual(0, e2.FailedLoginCount);
                        }
                        else
                        {
                            Assert.AreNotEqual(0, e1.FailedLoginCount);
                            Assert.AreNotEqual(0, e2.FailedLoginCount);
                        }
                    }
                    else
                    {
                        // the cycle will run and remove the expired ip first as they have finished the loop through the ban times, they should all have a single failed login count
                        AddFailedLogins(1);
                        AssertIPAddressesAreNotBanned(true, true);
                        Assert.IsTrue(service.DB.TryGetIPAddress(ip1, out IPBanDB.IPAddressEntry e1));
                        Assert.IsTrue(service.DB.TryGetIPAddress(ip2, out IPBanDB.IPAddressEntry e2));
                        Assert.IsNull(e1.BanStartDate);
                        Assert.IsNull(e2.BanStartDate);
                        Assert.IsNull(e1.BanEndDate);
                        Assert.IsNull(e2.BanEndDate);
                        Assert.AreEqual(1, e1.FailedLoginCount);
                        Assert.AreEqual(1, e2.FailedLoginCount);

                        // now add a bunch of fail logins, ip should ban with a time span of 1 minute
                        AddFailedLogins();
                        if (resetFailedLogin)
                        {
                            AssertIPAddressesAreBanned(0, 0);
                        }
                        else
                        {
                            AssertIPAddressesAreBanned(info1.Count + 1, info2.Count + 1);
                        }
                        Assert.IsTrue(service.DB.TryGetIPAddress(ip1, out e1));
                        Assert.IsTrue(service.DB.TryGetIPAddress(ip2, out e2));
                        TimeSpan expectedBanDuration = TimeSpan.FromMinutes(1.0);
                        Assert.AreEqual(expectedBanDuration, e1.BanEndDate - e1.BanStartDate);
                        Assert.AreEqual(expectedBanDuration, e2.BanEndDate - e2.BanStartDate);
                        if (resetFailedLogin)
                        {
                            Assert.AreEqual(0, e1.FailedLoginCount);
                            Assert.AreEqual(0, e2.FailedLoginCount);
                        }
                        else
                        {
                            Assert.AreEqual(info1.Count + 1, e1.FailedLoginCount);
                            Assert.AreEqual(info2.Count + 1, e2.FailedLoginCount);
                        }
                    }
                }
            }
            finally
            {
                // restore config
                await service.WriteConfigAsync(config);
            }
        }
Exemple #11
0
 public void Divide_Matrix_IsNotMatrix()
 {
     int[] falseArray = { 1, 2, 3, 4 };
     Assert.AreNotEqual(falseArray.GetType(), typeof(int));
 }
        public void BusinessSubscription_in_write_model_should_not_be_set()
        {
            var business = LoadAggregate <Business>(_businessId);

            Assert.AreNotEqual(_subscriptionId, business.SubscriptionId);
        }
 public object GetSharedComponentDataNonDefaultBoxed(int index)
 {
     Assert.AreNotEqual(0, index);
     return(m_SharedComponentData[index]);
 }
Exemple #14
0
        public void TestSkipNonSyncNetworkValues()
        {
            var writer = new BitStream(2048);
            var src    = new DE {
                SkipA = 1, SkipB = 2, SkipC = 3
            };

            _dynamicEntityFactoryBase.Write(writer, src);
            var buffer = writer.GetBuffer();

            var reader = new BitStream(buffer);
            var dest   = (DE)_dynamicEntityFactoryBase.Read(reader);

            Assert.AreEqual(src.Position, dest.Position);
            Assert.AreEqual(src.Size, dest.Size);
            Assert.AreEqual(src.Velocity, dest.Velocity);
            Assert.AreEqual(src.Weight, dest.Weight);
            Assert.AreEqual(src.MapEntityIndex, dest.MapEntityIndex);
            Assert.AreEqual(src.Center, dest.Center);

            Assert.AreEqual(src.A, dest.A);
            Assert.AreEqual(src.B, dest.B);
            Assert.AreEqual(src.C, dest.C);
            Assert.AreEqual(src.D, dest.D);
            Assert.AreEqual(src.E, dest.E);
            Assert.AreEqual(src.F, dest.F);
            Assert.AreEqual(src.G, dest.G);
            Assert.AreEqual(src.H, dest.H);
            Assert.AreEqual(src.I, dest.I);
            Assert.AreEqual(src.J, dest.J);
            Assert.AreEqual(src.K, dest.K);
            Assert.AreEqual(src.L, dest.L);
            Assert.AreEqual(src.M, dest.M);
            Assert.AreEqual(src.N, dest.N);
            Assert.AreEqual(src.O, dest.O);
            Assert.AreEqual(src.P, dest.P);
            Assert.AreEqual(src.Q, dest.Q);
            Assert.AreEqual(src.R, dest.R);

            Assert.AreNotEqual(src.SkipA, dest.SkipA);
            Assert.AreNotEqual(src.SkipB, dest.SkipB);
            Assert.AreEqual(src.SkipC, dest.SkipC);

            src.A = false;
            src.D = 100;
            src.K = 5123;
            src.N = "asfdoiuweroijsadf";
            src.P = Alignment.Left;
            src.M = new GrhIndex(10091);
            src.L = new Vector2(213, 123);
            src.Q = new Vector3(123, 412, 1931);
            src.R = new Vector4(109, 12, 190, 51);

            writer = new BitStream(2048);
            src.Serialize(writer);

            buffer = writer.GetBuffer();

            reader = new BitStream(buffer);
            dest.Deserialize(reader);

            Assert.AreEqual(src.Position, dest.Position);
            Assert.AreEqual(src.Size, dest.Size);
            Assert.AreEqual(src.Velocity, dest.Velocity);
            Assert.AreEqual(src.Weight, dest.Weight);
            Assert.AreEqual(src.MapEntityIndex, dest.MapEntityIndex);
            Assert.AreEqual(src.Center, dest.Center);

            Assert.AreEqual(src.A, dest.A);
            Assert.AreEqual(src.B, dest.B);
            Assert.AreEqual(src.C, dest.C);
            Assert.AreEqual(src.D, dest.D);
            Assert.AreEqual(src.E, dest.E);
            Assert.AreEqual(src.F, dest.F);
            Assert.AreEqual(src.G, dest.G);
            Assert.AreEqual(src.H, dest.H);
            Assert.AreEqual(src.I, dest.I);
            Assert.AreEqual(src.J, dest.J);
            Assert.AreEqual(src.K, dest.K);
            Assert.AreEqual(src.L, dest.L);
            Assert.AreEqual(src.M, dest.M);
            Assert.AreEqual(src.N, dest.N);
            Assert.AreEqual(src.O, dest.O);
            Assert.AreEqual(src.P, dest.P);
            Assert.AreEqual(src.Q, dest.Q);
            Assert.AreEqual(src.R, dest.R);

            Assert.AreNotEqual(src.SkipA, dest.SkipA);
            Assert.AreNotEqual(src.SkipB, dest.SkipB);
            Assert.AreEqual(src.SkipC, dest.SkipC);
        }
Exemple #15
0
        public void TestStructConstructor()
        {
            TestStructConstructor tsc = _faker.Create <TestStructConstructor>();

            Assert.AreNotEqual(tsc, default(TestStructConstructor));
        }
Exemple #16
0
        public void test_event_0()
        {
            testAgent.btsetcurrent("node_test/event_ut_0");
            testAgent.resetProperties();

            behaviac.EBTStatus status = testAgent.btexec();
            Assert.AreEqual(behaviac.EBTStatus.BT_RUNNING, status);

            testAgent.FireEvent("event_test_void");
            Assert.AreEqual(true, testAgent.event_test_var_bool);

            status = testAgent.btexec();
            Assert.AreEqual(behaviac.EBTStatus.BT_RUNNING, status);

            testAgent.resetProperties();
            testAgent.btsetcurrent("node_test/event_ut_0");
            testAgent.btexec();
            testAgent.FireEvent("event_test_int", 13);
            Assert.AreEqual(13, testAgent.event_test_var_int);

            status = testAgent.btexec();
            Assert.AreEqual(behaviac.EBTStatus.BT_RUNNING, status);

            testAgent.resetProperties();
            testAgent.btsetcurrent("node_test/event_ut_0");
            testAgent.btexec();
            testAgent.FireEvent("event_test_int_bool", 15, true);
            Assert.AreEqual(true, testAgent.event_test_var_bool);
            Assert.AreEqual(15, testAgent.event_test_var_int);

            status = testAgent.btexec();
            Assert.AreEqual(behaviac.EBTStatus.BT_RUNNING, status);

            testAgent.resetProperties();
            testAgent.btsetcurrent("node_test/event_ut_0");
            testAgent.btexec();
            testAgent.FireEvent("event_test_int_bool_float", 15, true, 27.3f);
            Assert.AreEqual(true, testAgent.event_test_var_bool);
            Assert.AreEqual(15, testAgent.event_test_var_int);
            Assert.AreEqual(27.3f, testAgent.event_test_var_float);

            status = testAgent.btexec();
            Assert.AreEqual(behaviac.EBTStatus.BT_RUNNING, status);

            testAgent.resetProperties();
            testAgent.btsetcurrent("node_test/event_ut_0");
            testAgent.btexec();
            testAgent.testVar_0 = 0;
            status = testAgent.btexec();
            Assert.AreEqual(behaviac.EBTStatus.BT_SUCCESS, status);
            Assert.AreEqual(0, testAgent.testVar_1);

            testAgent.FireEvent("event_test_int_bool_float", 19, true, 11.9f);
            Assert.AreEqual(false, testAgent.event_test_var_bool);
            Assert.AreEqual(-1, testAgent.event_test_var_int);
            Assert.AreEqual(-1.0f, testAgent.event_test_var_float);

            testAgent.resetProperties();
            testAgent.btsetcurrent("node_test/event_ut_0");
            status = testAgent.btexec();
            Assert.AreEqual(behaviac.EBTStatus.BT_RUNNING, status);

            Assert.AreEqual(null, testAgent.event_test_var_agent);
            testAgent.FireEvent("event_test_agent", testAgent);
            Assert.AreNotEqual(null, testAgent.event_test_var_agent);

            testAgent.resetProperties();
            testAgent.btsetcurrent("node_test/event_ut_0");
            testAgent.btresetcurrrent();
            status = testAgent.btexec();
            Assert.AreEqual(behaviac.EBTStatus.BT_RUNNING, status);

            Assert.AreEqual(null, testAgent.event_test_var_agent);
            testAgent.FireEvent("event_test_agent", testChild);
            Assert.AreNotEqual(null, testAgent.event_test_var_agent);
        }
Exemple #17
0
        public void HashPassword()
        {
            String clearpwd = "a random password with whitespaces";

            Assert.AreNotEqual(clearpwd, SevenLib.Helpers.HashHelper.HashString(clearpwd));
        }
 private void CheckIsNotEqual(ConfigFile configFile, string key, string expectedValue)
 {
     Assert.AreNotEqual(GetConfigValue(configFile.FileName, key), expectedValue, "git config --get");
     Assert.AreNotEqual(expectedValue, configFile.GetValue(key), "ConfigFile");
 }
Exemple #19
0
        public void ProductSyncListAddTwoEntriesRemoveSecond()
        {
            String settingsFileName = Path.GetTempFileName();

            File.Delete(settingsFileName);

            try
            {
                SettingsManager          settingsManager = new SettingsManager(settingsFileName);
                StackHashContextSettings contextSettings = settingsManager.CreateNewContextSettings();
                Assert.AreNotEqual(null, contextSettings.WinQualSettings.ProductsToSynchronize);

                settingsManager.SetProductSynchronization(0, 10, true);
                settingsManager.SetProductSynchronization(0, 20, true);
                StackHashSettings currentSettings = settingsManager.CurrentSettings;
                Assert.AreEqual(2, currentSettings.ContextCollection[0].WinQualSettings.ProductsToSynchronize.Count);
                StackHashProductSyncData productSyncData = currentSettings.ContextCollection[0].WinQualSettings.ProductsToSynchronize.FindProduct(10);
                Assert.AreNotEqual(null, productSyncData);
                Assert.AreEqual(10, productSyncData.ProductId);
                productSyncData = currentSettings.ContextCollection[0].WinQualSettings.ProductsToSynchronize.FindProduct(20);
                Assert.AreNotEqual(null, productSyncData);
                Assert.AreEqual(20, productSyncData.ProductId);

                // Check the settings are persisted.
                settingsManager = new SettingsManager(settingsFileName);
                currentSettings = settingsManager.CurrentSettings;
                Assert.AreEqual(2, currentSettings.ContextCollection[0].WinQualSettings.ProductsToSynchronize.Count);
                productSyncData = currentSettings.ContextCollection[0].WinQualSettings.ProductsToSynchronize.FindProduct(10);
                Assert.AreNotEqual(null, productSyncData);
                Assert.AreEqual(10, productSyncData.ProductId);
                productSyncData = currentSettings.ContextCollection[0].WinQualSettings.ProductsToSynchronize.FindProduct(20);
                Assert.AreNotEqual(null, productSyncData);
                Assert.AreEqual(20, productSyncData.ProductId);

                settingsManager.SetProductSynchronization(0, 20, false);
                currentSettings = settingsManager.CurrentSettings;
                Assert.AreEqual(1, currentSettings.ContextCollection[0].WinQualSettings.ProductsToSynchronize.Count);
                productSyncData = currentSettings.ContextCollection[0].WinQualSettings.ProductsToSynchronize.FindProduct(10);
                Assert.AreNotEqual(null, productSyncData);
                Assert.AreEqual(10, productSyncData.ProductId);
                productSyncData = currentSettings.ContextCollection[0].WinQualSettings.ProductsToSynchronize.FindProduct(20);
                Assert.AreEqual(null, productSyncData);

                // Check the settings are persisted.
                settingsManager = new SettingsManager(settingsFileName);
                currentSettings = settingsManager.CurrentSettings;
                Assert.AreEqual(1, currentSettings.ContextCollection[0].WinQualSettings.ProductsToSynchronize.Count);
                productSyncData = currentSettings.ContextCollection[0].WinQualSettings.ProductsToSynchronize.FindProduct(10);
                Assert.AreNotEqual(null, productSyncData);
                Assert.AreEqual(10, productSyncData.ProductId);
                productSyncData = currentSettings.ContextCollection[0].WinQualSettings.ProductsToSynchronize.FindProduct(20);
                Assert.AreEqual(null, productSyncData);
            }
            finally
            {
                if (File.Exists(settingsFileName))
                {
                    File.Delete(settingsFileName);
                }
            }
        }
Exemple #20
0
        public void TestA()
        {
            A a = _faker.Create <A>();

            Assert.AreNotEqual(a, default(A));
        }
        public void CloudFileCopyIgnoreReadOnlyAndSetArchiveTest()
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                share.Create();

                // Create Source on server
                CloudFile source = share.GetRootDirectoryReference().GetFileReference("source");

                string data = "String data";
                UploadText(source, data, Encoding.UTF8);

                // Create Destination on server
                CloudFile destination = share.GetRootDirectoryReference().GetFileReference("destination");
                destination.Create(1);

                destination.Properties.NtfsAttributes = CloudFileNtfsAttributes.Hidden | CloudFileNtfsAttributes.ReadOnly;
                destination.SetProperties();

                string permission    = "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;S-1-5-21-397955417-626881126-188441444-3053964)";
                string permissionKey = share.CreateFilePermission(permission);
                destination.Properties.FilePermissionKey = permissionKey;

                CloudFile copySource      = source;
                CloudFile copyDestination = destination;

                // Start copy and wait for completion
                string copyId = copyDestination.StartCopy(TestHelper.Defiddler(copySource),
                                                          null,
                                                          null,
                                                          new FileCopyOptions()
                {
                    PreservePermissions = false,
                    IgnoreReadOnly      = true,
                    SetArchive          = true
                },
                                                          null,
                                                          null);

                WaitForCopy(destination);

                // Check original file references for equality
                Assert.AreEqual(CopyStatus.Success, destination.CopyState.Status);
                Assert.AreEqual(source.Uri.AbsolutePath, destination.CopyState.Source.AbsolutePath);
                Assert.AreEqual(data.Length, destination.CopyState.TotalBytes);
                Assert.AreEqual(data.Length, destination.CopyState.BytesCopied);
                Assert.AreEqual(copyId, destination.CopyState.CopyId);
                Assert.IsTrue(destination.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                TestHelper.ExpectedException(
                    () => copyDestination.AbortCopy(copyId),
                    "Aborting a copy operation after completion should fail",
                    HttpStatusCode.Conflict,
                    "NoPendingCopyOperation");

                source.FetchAttributes();
                Assert.IsNotNull(destination.Properties.ETag);
                Assert.AreNotEqual(source.Properties.ETag, destination.Properties.ETag);
                Assert.IsTrue(destination.Properties.LastModified > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                string copyData = DownloadText(destination, Encoding.UTF8);
                Assert.AreEqual(data, copyData, "Data inside copy of file not equal.");

                destination.FetchAttributes();
                FileProperties prop1 = destination.Properties;
                FileProperties prop2 = source.Properties;

                Assert.AreEqual(prop1.CacheControl, prop2.CacheControl);
                Assert.AreEqual(prop1.ContentEncoding, prop2.ContentEncoding);
                Assert.AreEqual(prop1.ContentLanguage, prop2.ContentLanguage);
                Assert.AreEqual(prop1.ContentMD5, prop2.ContentMD5);
                Assert.AreEqual(prop1.ContentType, prop2.ContentType);
                Assert.AreEqual(CloudFileNtfsAttributes.Archive, destination.Properties.NtfsAttributes.Value);
                Assert.IsNotNull(destination.Properties.FilePermissionKey);
                Assert.IsNull(destination.FilePermission);

                destination.Delete();
                source.Delete();
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
Exemple #22
0
        public void TestB()
        {
            B b = _faker.Create <B>();

            Assert.AreNotEqual(b, default(B));
        }
        private static void CloudFileCopy(bool sourceIsSas, bool destinationIsSas)
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                share.Create();

                // Create Source on server
                CloudFile source = share.GetRootDirectoryReference().GetFileReference("source");

                string data = "String data";
                UploadText(source, data, Encoding.UTF8);

                source.Metadata["Test"] = "value";
                source.SetMetadata();

                string permission    = "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;S-1-5-21-397955417-626881126-188441444-3053964)";
                string permissionKey = share.CreateFilePermission(permission);
                source.Properties.FilePermissionKey = permissionKey;

                var attributes   = CloudFileNtfsAttributes.NoScrubData | CloudFileNtfsAttributes.Temporary;
                var creationTime = DateTimeOffset.UtcNow.AddDays(-1);

                source.Properties.NtfsAttributes = attributes;
                DateTimeOffset lastWriteTime = DateTimeOffset.UtcNow;
                source.Properties.LastWriteTime = lastWriteTime;

                source.Properties.CreationTime = creationTime;
                source.SetProperties();

                // Create Destination on server
                CloudFile destination = share.GetRootDirectoryReference().GetFileReference("destination");
                destination.Create(1);

                CloudFile copySource      = source;
                CloudFile copyDestination = destination;

                if (sourceIsSas)
                {
                    // Source SAS must have read permissions
                    SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Read;
                    SharedAccessFilePolicy      policy      = new SharedAccessFilePolicy()
                    {
                        SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                        SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                        Permissions            = permissions,
                    };

                    string sasToken = share.GetSharedAccessSignature(policy);

                    // Get source
                    StorageCredentials credentials = new StorageCredentials(sasToken);
                    copySource = new CloudFile(credentials.TransformUri(source.Uri));
                }

                if (destinationIsSas)
                {
                    Assert.IsTrue(sourceIsSas);

                    // Destination SAS must have write permissions
                    SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Write;
                    SharedAccessFilePolicy      policy      = new SharedAccessFilePolicy()
                    {
                        SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                        SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                        Permissions            = permissions,
                    };
                    string sasToken = destination.GetSharedAccessSignature(policy);

                    // Get destination
                    StorageCredentials credentials = new StorageCredentials(sasToken);
                    copyDestination = new CloudFile(credentials.TransformUri(destination.Uri));
                }

                // Start copy and wait for completion
                string copyId = copyDestination.StartCopy(TestHelper.Defiddler(copySource),
                                                          null,
                                                          null,
                                                          new FileCopyOptions()
                {
                    PreservePermissions    = true,
                    PreserveCreationTime   = true,
                    PreserveLastWriteTime  = true,
                    PreserveNtfsAttributes = true,
                    SetArchive             = false
                },
                                                          null, null);

                WaitForCopy(destination);

                // Check original file references for equality
                Assert.AreEqual(CopyStatus.Success, destination.CopyState.Status);
                Assert.AreEqual(source.Uri.AbsolutePath, destination.CopyState.Source.AbsolutePath);
                Assert.AreEqual(data.Length, destination.CopyState.TotalBytes);
                Assert.AreEqual(data.Length, destination.CopyState.BytesCopied);
                Assert.AreEqual(copyId, destination.CopyState.CopyId);
                Assert.IsTrue(destination.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                if (!destinationIsSas)
                {
                    // Abort Copy is not supported for SAS destination
                    TestHelper.ExpectedException(
                        () => copyDestination.AbortCopy(copyId),
                        "Aborting a copy operation after completion should fail",
                        HttpStatusCode.Conflict,
                        "NoPendingCopyOperation");
                }

                source.FetchAttributes();
                Assert.IsNotNull(destination.Properties.ETag);
                Assert.AreNotEqual(source.Properties.ETag, destination.Properties.ETag);
                Assert.IsTrue(destination.Properties.LastModified > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                string copyData = DownloadText(destination, Encoding.UTF8);
                Assert.AreEqual(data, copyData, "Data inside copy of file not equal.");

                destination.FetchAttributes();
                FileProperties prop1 = destination.Properties;
                FileProperties prop2 = source.Properties;

                Assert.AreEqual(prop1.CacheControl, prop2.CacheControl);
                Assert.AreEqual(prop1.ContentEncoding, prop2.ContentEncoding);
                Assert.AreEqual(prop1.ContentLanguage, prop2.ContentLanguage);
                Assert.AreEqual(prop1.ContentMD5, prop2.ContentMD5);
                Assert.AreEqual(prop1.ContentType, prop2.ContentType);
                Assert.AreEqual(lastWriteTime, destination.Properties.LastWriteTime.Value);
                Assert.AreEqual(creationTime, destination.Properties.CreationTime.Value);
                Assert.AreEqual(attributes, destination.Properties.NtfsAttributes.Value);
                Assert.IsNotNull(destination.Properties.FilePermissionKey);
                Assert.IsNull(destination.FilePermission);

                Assert.AreEqual("value", destination.Metadata["Test"], false, "Copied metadata not same");

                destination.Delete();
                source.Delete();
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
Exemple #24
0
        public void TestC()
        {
            C c = _faker.Create <C>();

            Assert.AreNotEqual(c, default(C));
        }
Exemple #25
0
        public void RunBFSAndCheck <TVertex, TEdge>(
            IVertexAndEdgeListGraph <TVertex, TEdge> graph,
            TVertex sourceVertex)
            where TEdge : IEdge <TVertex>
        {
            var     parents         = new Dictionary <TVertex, TVertex>();
            var     distances       = new Dictionary <TVertex, int>();
            TVertex currentVertex   = default;
            int     currentDistance = 0;
            var     algorithm       = new BreadthFirstSearchAlgorithm <TVertex, TEdge>(graph);

            algorithm.InitializeVertex += vertex =>
            {
                Assert.AreEqual(GraphColor.White, algorithm.VerticesColors[vertex]);
            };

            algorithm.StartVertex += vertex =>
            {
                Assert.AreEqual(GraphColor.White, algorithm.VerticesColors[vertex]);
            };

            algorithm.DiscoverVertex += vertex =>
            {
                Assert.AreEqual(GraphColor.Gray, algorithm.VerticesColors[vertex]);
                if (vertex.Equals(sourceVertex))
                {
                    currentVertex = sourceVertex;
                }
                else
                {
                    Assert.IsNotNull(currentVertex);
                    Assert.AreEqual(parents[vertex], currentVertex);
                    // ReSharper disable once AccessToModifiedClosure
                    Assert.AreEqual(distances[vertex], currentDistance + 1);
                    Assert.AreEqual(distances[vertex], distances[parents[vertex]] + 1);
                }
            };

            algorithm.ExamineEdge += edge =>
            {
                Assert.AreEqual(edge.Source, currentVertex);
            };

            algorithm.ExamineVertex += vertex =>
            {
                TVertex u = vertex;
                currentVertex = u;
                // Ensure that the distances monotonically increase.
                // ReSharper disable AccessToModifiedClosure
                Assert.IsTrue(distances[u] == currentDistance || distances[u] == currentDistance + 1);

                if (distances[u] == currentDistance + 1) // New level
                {
                    ++currentDistance;
                }
                // ReSharper restore AccessToModifiedClosure
            };

            algorithm.TreeEdge += edge =>
            {
                TVertex u = edge.Source;
                TVertex v = edge.Target;

                Assert.AreEqual(GraphColor.White, algorithm.VerticesColors[v]);
                Assert.AreEqual(distances[u], currentDistance);
                parents[v]   = u;
                distances[v] = distances[u] + 1;
            };

            algorithm.NonTreeEdge += edge =>
            {
                TVertex u = edge.Source;
                TVertex v = edge.Target;

                Assert.IsFalse(algorithm.VerticesColors[v] == GraphColor.White);

                if (algorithm.VisitedGraph.IsDirected)
                {
                    // Cross or back edge
                    Assert.IsTrue(distances[v] <= distances[u] + 1);
                }
                else
                {
                    // Cross edge (or going backwards on a tree edge)
                    Assert.IsTrue(
                        distances[v] == distances[u] ||
                        distances[v] == distances[u] + 1 ||
                        distances[v] == distances[u] - 1);
                }
            };

            algorithm.GrayTarget += edge =>
            {
                Assert.AreEqual(GraphColor.Gray, algorithm.VerticesColors[edge.Target]);
            };

            algorithm.BlackTarget += edge =>
            {
                Assert.AreEqual(GraphColor.Black, algorithm.VerticesColors[edge.Target]);

                foreach (TEdge outEdge in algorithm.VisitedGraph.OutEdges(edge.Target))
                {
                    Assert.IsFalse(algorithm.VerticesColors[outEdge.Target] == GraphColor.White);
                }
            };

            algorithm.FinishVertex += vertex =>
            {
                Assert.AreEqual(GraphColor.Black, algorithm.VerticesColors[vertex]);
            };

            parents.Clear();
            distances.Clear();
            currentDistance = 0;

            foreach (TVertex vertex in graph.Vertices)
            {
                distances[vertex] = int.MaxValue;
                parents[vertex]   = vertex;
            }

            distances[sourceVertex] = 0;

            var recorder = new VertexPredecessorRecorderObserver <TVertex, TEdge>();

            using (recorder.Attach(algorithm))
            {
                algorithm.Compute(sourceVertex);
            }

            // All white vertices should be unreachable from the source.
            foreach (TVertex vertex in graph.Vertices)
            {
                if (algorithm.VerticesColors[vertex] == GraphColor.White)
                {
                    // Check !IsReachable(sourceVertex, vertex, graph);
                    if (recorder.TryGetPath(vertex, out IEnumerable <TEdge> path))
                    {
                        foreach (TEdge edge in path)
                        {
                            Assert.AreNotEqual(sourceVertex, edge.Source);
                            Assert.AreNotEqual(sourceVertex, edge.Target);
                        }
                    }
                }
            }

            // The shortest path to a child should be one longer than
            // shortest path to the parent.
            foreach (TVertex vertex in graph.Vertices)
            {
                if (!parents[vertex].Equals(vertex)) // Not the root of the BFS tree
                {
                    Assert.AreEqual(distances[vertex], distances[parents[vertex]] + 1);
                }
            }
        }
Exemple #26
0
        public void TestPrivateProperty()
        {
            PrivateProperty pp = _faker.Create <PrivateProperty>();

            Assert.AreNotEqual(pp, default(PrivateProperty));
        }
Exemple #27
0
        public void ComputeMarginProperlyAsSecurityPriceFluctuates()
        {
            const int quantity     = 1000;
            var       securities   = new SecurityManager();
            var       transactions = new SecurityTransactionManager(securities);
            var       portfolio    = new SecurityPortfolioManager(securities, transactions);

            portfolio.CashBook["USD"].Quantity = quantity;

            var config = new SubscriptionDataConfig(typeof(TradeBar), SecurityType.Equity, "AAPL", Resolution.Minute, true, true, true, true, true, 0);

            securities.Add(new Security(config, 1, false));

            var           time     = DateTime.Now;
            const decimal buyPrice = 1m;

            securities["AAPL"].SetMarketPrice(time, new TradeBar(time, "AAPL", buyPrice, buyPrice, buyPrice, buyPrice, 1));

            var order = new MarketOrder("AAPL", quantity, time)
            {
                Price = buyPrice
            };
            var fill = new OrderEvent(order)
            {
                FillPrice = buyPrice, FillQuantity = quantity
            };

            Assert.AreEqual(portfolio.CashBook["USD"].Quantity, fill.FillPrice * fill.FillQuantity);

            portfolio.ProcessFill(fill);

            Assert.AreEqual(0, portfolio.MarginRemaining);
            Assert.AreEqual(quantity, portfolio.TotalMarginUsed);
            Assert.AreEqual(quantity, portfolio.TotalPortfolioValue);

            // we shouldn't be able to place a trader
            var newOrder = new MarketOrder("AAPL", 1, time.AddSeconds(1))
            {
                Price = buyPrice
            };
            bool sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder);

            Assert.IsFalse(sufficientCapital);

            // now the stock doubles, so we should have margin remaining

            time = time.AddDays(1);
            const decimal highPrice = buyPrice * 2;

            securities["AAPL"].SetMarketPrice(time, new TradeBar(time, "AAPL", highPrice, highPrice, highPrice, highPrice, 1));

            Assert.AreEqual(quantity, portfolio.MarginRemaining);
            Assert.AreEqual(quantity, portfolio.TotalMarginUsed);
            Assert.AreEqual(quantity * 2, portfolio.TotalPortfolioValue);

            // we shouldn't be able to place a trader
            var anotherOrder = new MarketOrder("AAPL", 1, time.AddSeconds(1))
            {
                Price = highPrice
            };

            sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, anotherOrder);
            Assert.IsTrue(sufficientCapital);

            // now the stock plummets, so we should have negative margin remaining

            time = time.AddDays(1);
            const decimal lowPrice = buyPrice / 2;

            securities["AAPL"].SetMarketPrice(time, new TradeBar(time, "AAPL", lowPrice, lowPrice, lowPrice, lowPrice, 1));

            Assert.AreEqual(-quantity / 2m, portfolio.MarginRemaining);
            Assert.AreEqual(quantity, portfolio.TotalMarginUsed);
            Assert.AreEqual(quantity / 2m, portfolio.TotalPortfolioValue);


            // this would cause a margin call
            var marginCallOrders = portfolio.ScanForMarginCall();

            Assert.AreNotEqual(0, marginCallOrders.Count);
            Assert.AreEqual(-quantity, marginCallOrders[0].Quantity);
            Assert.GreaterOrEqual(-portfolio.MarginRemaining, marginCallOrders[0].Price * marginCallOrders[0].Quantity);
        }
Exemple #28
0
        public void TestListClass()
        {
            List <TestClass> l = _faker.Create <List <TestClass> >();

            Assert.AreNotEqual(l, default(List <TestClass>));
        }
        public void CopyConstructorsTest()
        {
            string     schema   = $@"
namespace CopyConstructorTest;

union Union {{ OuterTable, InnerTable, OuterStruct, InnerStruct }} // Optionally add more tables.

table OuterTable ({MetadataKeys.SerializerKind}: ""Greedy"") {{
  A:string;

  B:byte;
  C:ubyte;
  D:int16;
  E:uint16;
  F:int32;
  G:uint32;
  H:int64;
  I:uint64;
  
  IntVector_List:[int] ({MetadataKeys.VectorKind}:""IList"");
  IntVector_RoList:[int] ({MetadataKeys.VectorKind}:""IReadOnlyList"");
  IntVector_Array:[int] ({MetadataKeys.VectorKind}:""Array"");
  
  TableVector_List:[InnerTable] ({MetadataKeys.VectorKind}:""IList"");
  TableVector_RoList:[InnerTable] ({MetadataKeys.VectorKind}:""IReadOnlyList"");
  TableVector_Indexed:[InnerTable] ({MetadataKeys.VectorKind}:""IIndexedVector"");
  TableVector_Array:[InnerTable] ({MetadataKeys.VectorKindLegacy}:""Array"");

  ByteVector:[ubyte] ({MetadataKeys.VectorKind}:""Memory"");
  ByteVector_RO:[ubyte] ({MetadataKeys.VectorKind}:""ReadOnlyMemory"");
  Union:Union;
}}

struct OuterStruct {{
    Value:int;
    InnerStruct:InnerStruct;
}}

struct InnerStruct {{
    LongValue:int64;
}}

table InnerTable {{
  Name:string ({MetadataKeys.Key});
  OuterStruct:OuterStruct;
}}

";
            OuterTable original = new OuterTable
            {
                A = "string",
                B = 1,
                C = 2,
                D = 3,
                E = 4,
                F = 5,
                G = 6,
                H = 7,
                I = 8,

                ByteVector = new byte[] { 1, 2, 3, }.AsMemory(),
                       ByteVector_RO = new byte[] { 4, 5, 6, }.AsMemory(),

                       IntVector_Array = new[] { 7, 8, 9, },
                       IntVector_List = new[] { 10, 11, 12, }.ToList(),
                       IntVector_RoList = new[] { 13, 14, 15 }.ToList(),

                       TableVector_Array   = CreateInner("Rocket", "Molly", "Jingle"),
                       TableVector_Indexed = new IndexedVector <string, InnerTable>(CreateInner("Pudge", "Sunshine", "Gypsy"), false),
                       TableVector_List    = CreateInner("Finnegan", "Daisy"),
                       TableVector_RoList  = CreateInner("Gordita", "Lunchbox"),

                       Union = new FlatBufferUnion <OuterTable, InnerTable, OuterStruct, InnerStruct>(new OuterStruct())
            };

            byte[] data         = new byte[FlatBufferSerializer.Default.GetMaxSize(original)];
            int    bytesWritten = FlatBufferSerializer.Default.Serialize(original, data);

            Assembly asm = FlatSharpCompiler.CompileAndLoadAssembly(schema, new());

            Type    outerTableType = asm.GetType("CopyConstructorTest.OuterTable");
            dynamic serializer     = outerTableType.GetProperty("Serializer", BindingFlags.Public | BindingFlags.Static).GetValue(null);
            object  parsedObj      = serializer.Parse(new ArrayInputBuffer(data));
            dynamic parsed         = parsedObj;
            dynamic copied         = Activator.CreateInstance(outerTableType, (object)parsed);

            //dynamic copied = new CopyConstructorTest.OuterTable((CopyConstructorTest.OuterTable)parsedObj);

            // Strings can be copied by reference since they are immutable.
            Assert.AreEqual(original.A, copied.A);
            Assert.AreEqual(original.A, parsed.A);

            Assert.AreEqual(original.B, copied.B);
            Assert.AreEqual(original.C, copied.C);
            Assert.AreEqual(original.D, copied.D);
            Assert.AreEqual(original.E, copied.E);
            Assert.AreEqual(original.F, copied.F);
            Assert.AreEqual(original.G, copied.G);
            Assert.AreEqual(original.H, copied.H);
            Assert.AreEqual(original.I, copied.I);

            Assert.AreEqual((byte)3, original.Union.Discriminator);
            Assert.AreEqual((byte)3, parsed.Union.Discriminator);
            Assert.AreEqual((byte)3, copied.Union.Discriminator);
            Assert.AreEqual("CopyConstructorTest.OuterStruct", copied.Union.Item3.GetType().FullName);
            Assert.AreNotEqual("CopyConstructorTest.OuterStruct", parsed.Union.Item3.GetType().FullName);
            Assert.AreNotSame(parsed.Union, copied.Union);
            Assert.AreNotSame(parsed.Union.Item3, copied.Union.Item3);

            Memory <byte>?mem  = copied.ByteVector;
            Memory <byte>?pMem = parsed.ByteVector;

            Assert.IsTrue(original.ByteVector.Value.Span.SequenceEqual(mem.Value.Span));
            Assert.IsFalse(mem.Value.Span.Overlaps(pMem.Value.Span));

            ReadOnlyMemory <byte>?roMem  = copied.ByteVector_RO;
            ReadOnlyMemory <byte>?pRoMem = parsed.ByteVector_RO;

            Assert.IsTrue(original.ByteVector_RO.Value.Span.SequenceEqual(roMem.Value.Span));
            Assert.IsFalse(roMem.Value.Span.Overlaps(pRoMem.Value.Span));

            // array of table
            {
                int count = original.TableVector_Array.Length;
                Assert.AreNotSame(parsed.TableVector_Array, copied.TableVector_Array);
                for (int i = 0; i < count; ++i)
                {
                    var p = parsed.TableVector_Array[i];
                    var c = copied.TableVector_Array[i];
                    DeepCompareInnerTable(original.TableVector_Array[i], p, c);
                }
            }

            // list of table.
            {
                Assert.IsFalse(object.ReferenceEquals(parsed.TableVector_List, copied.TableVector_List));

                IEnumerable <object> parsedEnum = AsObjectEnumerable(parsed.TableVector_List);
                IEnumerable <object> copiedEnum = AsObjectEnumerable(copied.TableVector_List);

                foreach (var((p, c), o) in parsedEnum.Zip(copiedEnum).Zip(original.TableVector_List))
                {
                    DeepCompareInnerTable(o, p, c);
                }
            }

            // read only list of table.
            {
                Assert.IsFalse(object.ReferenceEquals(parsed.TableVector_RoList, copied.TableVector_RoList));

                IEnumerable <object> parsedEnum = AsObjectEnumerable(parsed.TableVector_RoList);
                IEnumerable <object> copiedEnum = AsObjectEnumerable(copied.TableVector_RoList);

                foreach (var((p, c), o) in parsedEnum.Zip(copiedEnum).Zip(original.TableVector_RoList))
                {
                    DeepCompareInnerTable(o, p, c);
                }
            }

            // indexed vector of table.
            {
                Assert.IsFalse(object.ReferenceEquals(parsed.TableVector_Indexed, copied.TableVector_Indexed));
                foreach (var kvp in original.TableVector_Indexed)
                {
                    string     key   = kvp.Key;
                    InnerTable?value = kvp.Value;

                    var parsedValue = parsed.TableVector_Indexed[key];
                    var copiedValue = copied.TableVector_Indexed[key];

                    Assert.IsNotNull(parsedValue);
                    Assert.IsNotNull(copiedValue);

                    DeepCompareInnerTable(value, parsedValue, copiedValue);
                }
            }
        }
Exemple #30
0
 public void AddFieldObject_ToRowObject_NullFieldObject()
 {
     RowObject rowObject = new RowObject();
     rowObject = (RowObject)OptionObjectHelpers.AddFieldObject(rowObject, null);
     Assert.AreNotEqual(rowObject, null);
 }