//导出单条数据
        private void ExportSingleDataToPath(string folderPath, string dataBaseName, WimsGridView wimsGridView)
        {
            Cursor.Current = Cursors.WaitCursor;
            if (Directory.Exists(folderPath))
            {
                Directory.Delete(folderPath, true);
            }
            Directory.CreateDirectory(folderPath);
            switch (dataBaseName)
            {
            case "Command":
                Command        Entity      = wimsGridView.FindFirstSelect <Command>();
                List <Command> commandList = new List <Command>();
                commandList.Add(Entity);
                BackupDataBll <Command> .ExportSingleData(folderPath, commandList);

                break;

            case "Dut":
                Dut        dutEntity = wimsGridView.FindFirstSelect <Dut>();
                List <Dut> dutList   = new List <Dut>();
                dutList.Add(dutEntity);
                BackupDataBll <Dut> .ExportSingleData(folderPath, dutList);

                break;

            case "Project":
                Project        projectEntity = wimsGridView.FindFirstSelect <Project>();
                List <Project> projectList   = new List <Project>();
                projectList.Add(projectEntity);
                BackupDataBll <Project> .ExportSingleData(folderPath, projectList);

                break;

            case "TestCase":
                TestCase        testCaseEntity = wimsGridView.FindFirstSelect <TestCase>();
                List <TestCase> testCaseList   = new List <TestCase>();
                testCaseList.Add(testCaseEntity);
                BackupDataBll <TestCase> .ExportSingleData(folderPath, testCaseList);

                break;

            case "TestDevice":
                TestDevice        testDeviceEntity = wimsGridView.FindFirstSelect <TestDevice>();
                List <TestDevice> testDeviceList   = new List <TestDevice>();
                testDeviceList.Add(testDeviceEntity);
                BackupDataBll <TestDevice> .ExportSingleData(folderPath, testDeviceList);

                break;

            case "TestParams":
                TestParams        testParamsEntity = wimsGridView.FindFirstSelect <TestParams>();
                List <TestParams> testParamsList   = new List <TestParams>();
                testParamsList.Add(testParamsEntity);
                BackupDataBll <TestParams> .ExportSingleData(folderPath, testParamsList);

                break;
            }
            Cursor.Current = Cursors.Default;
        }
Ejemplo n.º 2
0
        private static async Task TestMassiveFileQuantity(CancellationToken cancellationToken)
        {
            var options = new TestParams()
            {
                CacheOptions = new HybridCacheOptions(null)
                {
                    AsyncCacheOptions = new AsyncCacheOptions()
                    {
                        MaxQueuedBytes = 0,
                        FailRequestsOnEnqueueLockTimeout = true,
                        WriteSynchronouslyWhenQueueFull  = true,
                    },
                    CleanupManagerOptions = new CleanupManagerOptions()
                    {
                        MaxCacheBytes   = (long)4096 * 2 * 1000 * 1000, // 1/2th the size of the files we are trying to write
                        MinAgeToDelete  = TimeSpan.Zero,
                        MinCleanupBytes = 0,                            //1 * 1000 * 1000,
                    }
                },
                FileSize                 = 64,
                FileCount                = 60000,
                RequestCountPerWave      = 2000,
                RequestWaves             = 5,
                RequestWavesIntermission = TimeSpan.Zero,
                CreationTaskDelay        = TimeSpan.FromMilliseconds(0),
                CreationThreadSleep      = TimeSpan.FromMilliseconds(0),
                DisplayLog               = true
            };

            Console.WriteLine("Starting HybridCache test async disabled and 60,000 files in waves of 2000 requests");
            await TestRandom(options, cancellationToken);
        }
Ejemplo n.º 3
0
        private static async Task TestRandomAsyncVeryLimitedCache(CancellationToken cancellationToken)
        {
            var options = new TestParams()
            {
                CacheOptions = new HybridCacheOptions(null)
                {
                    AsyncCacheOptions = new AsyncCacheOptions()
                    {
                        MaxQueuedBytes = 100 * 1000 * 1000,
                        FailRequestsOnEnqueueLockTimeout = true,
                        WriteSynchronouslyWhenQueueFull  = true,
                    },
                    CleanupManagerOptions = new CleanupManagerOptions()
                    {
                        MaxCacheBytes   = 8192000, // 1/5th the size of the files we are trying to write
                        MinAgeToDelete  = TimeSpan.Zero,
                        MinCleanupBytes = 0,
                    },
                    Subfolders = 1
                },
                FileSize                 = 81920,
                FileCount                = 500,
                RequestCountPerWave      = 2000,
                RequestWaves             = 5,
                RequestWavesIntermission = TimeSpan.FromSeconds(1),
                CreationTaskDelay        = TimeSpan.FromMilliseconds(1000),
                CreationThreadSleep      = TimeSpan.FromMilliseconds(0),
                DisplayLog               = false
            };

            Console.WriteLine("Starting HybridCache test with the async queue enabled and the cache limited to 1/5th the needed size");
            await TestRandom(options, cancellationToken);
        }
Ejemplo n.º 4
0
        async Task FillTestParams(TradingMacro tmOriginal, Action <IList <KeyValuePair <string, object>[]> > paramsTransformation)
        {
            var c = _testParamValuesSeparators;

            if (!_testParamsRaw.Any())
            {
                if (!ReplayArguments.IsWww && tmOriginal.UseTestFile)
                {
                    var od = new Microsoft.Win32.OpenFileDialog()
                    {
                        FileName = "TestParams", DefaultExt = ".txt", Filter = "Text documents(.txt)|*.txt"
                    };
                    var odRes = od.ShowDialog();
                    if (!odRes.GetValueOrDefault())
                    {
                        throw new ArgumentException("Must provide test params file name.");
                    }
                    tmOriginal.TestFileName = System.IO.Path.GetFileName(od.FileName);
                    if (tmOriginal.TestFileName.Contains("skipme"))
                    {
                        tmOriginal.TestFileName = "";
                    }
                    else
                    {
                        var paramsDict = Lib.ReadTestParameters(od.FileName);
                        _testParamsRaw.AddRange(paramsDict.Select(kv => kv.Value.Split(c).Select(v => new KeyValuePair <string, object>(kv.Key, v)).ToArray()));
                    }
                }
                else if (ReplayArguments.IsWww)
                {
                    ReplayArguments.LastWwwError = "";
                    var strats = TaskMonad.RunSync(() => ReadStrategies(tmOriginal, (name, desc, content, uri, diff) => new { name, content, diff }));
                    Func <string, bool> isTest = s => s.ToLower().Trim().EndsWith("{t}");
                    await strats.Select(s => s.First())
                    .Take(2)
                    .OrderByDescending(s => isTest(s.name))
                    .Where(s => isTest(s.name) || s.diff.IsEmpty())
                    .OnEmpty(() => { LogWww(new Exception(ReplayArguments.LastWwwError = "Current settings don't match any strategy")); })
                    .Select(strategy => {
                        tmOriginal.TestFileName = strategy.name;
                        var paramsDict          = Lib.ReadParametersFromString(strategy.content);
                        _testParamsRaw.AddRange(
                            paramsDict
                            .Select(kv => kv.Value.Split(c).Select(v => new KeyValuePair <string, object>(kv.Key, v))
                                    .ToArray()));
                        return(tmOriginal.LoadActiveSettings(strategy.name, TradingMacro.ActiveSettingsStore.Gist));
                    }).WhenAll();
                }
                else
                {
                    var testParams = tmOriginal.GetPropertiesByAttibute <CategoryAttribute>(a => a.Category == TradingMacro.categoryTest);
                    var paramsDict = testParams.ToDictionary(p => p.Item2.Name.Substring(4), p => p.Item2.GetValue(tmOriginal, null).ToString().ParseParamRange());
                    _testParamsRaw.AddRange(paramsDict.Where(kv => !string.IsNullOrWhiteSpace(kv.Value))
                                            .Select(kv => kv.Value.Split(c).Select(v => new KeyValuePair <string, object>(kv.Key, v)).ToArray()));
                }
            }
            TestParams.Clear();
            paramsTransformation(_testParamsRaw);
            _testParamsRaw.CartesianProduct().ForEach(tp => TestParams.Enqueue(tp.ToArray()));
        }
Ejemplo n.º 5
0
        public static void Init(string parametersFile)
        {
            TextReader reader = new StreamReader(parametersFile);

            XmlSerializer serializer = new XmlSerializer(typeof(TestParams));
            TestParams = (TestParams)serializer.Deserialize(reader);
        }
Ejemplo n.º 6
0
        async Task StartReplay(TradingMacro tm)
        {
            TradingMacro tmOriginal = (TradingMacro)tm;

            if (!IsLoggedIn)
            {
                LogWww(new Exception("Must login first."));
                return;
            }

            try {
                while (_replayTasks.ToArray().Any(t => t.Status == TaskStatus.Running))
                {
                    if (ReplayArguments.IsWww)
                    {
                        ReplayArguments.LastWwwError = "Replay is running";
                        return;
                    }
                    Log = new Exception("Replay is running.");
                    Thread.Sleep(1000);
                    continue;
                }

                ReplayArguments.Initiator       = tmOriginal;
                ReplayArguments.StartingBalance = tmOriginal.TestBalance;
                ReplayArguments.PrevSessionUid  = tmOriginal.TestPrevSession;
                ReplayArguments.SuperSessionId  = tmOriginal.TestSuperSessionUid.ValueOrDefault(Guid.NewGuid());
                _testParamsRaw.Clear();
                tmOriginal.TestFileName = "";

                if (ReplayArguments.UseSuperSession)
                {
                    #region getDateFromSuperSession
                    Func <Task <DateTime> > getDateFromSuperSession = async() => {
                        try {
                            var sessions = GetBestSessions(ReplayArguments.SuperSessionId).ToArray();
                            if (sessions.Any())
                            {
                                await FillTestParams(tmOriginal, tpr => { });
                            }
                            else
                            {
                                throw new Exception("Either ReplayArguments.DateStart or valid Supersession Uid must be provided.");
                            }
                            return(sessions.Min(s => s.DateStart.Value).AddDays(5));
                        } catch (Exception exc) {
                            Log = exc;
                            throw;
                        }
                    };
                    #endregion
                    ReplayArguments.DateStart = ReplayArguments.DateStart ?? await getDateFromSuperSession();
                }
                await FillTestParams(tmOriginal, pt => { });

                Log = new Exception("Starting testing with {0} sets.".Formater(TestParams.Count));
                StartReplayInternal(tmOriginal, TestParams.Any() ? TestParams.Dequeue() : null, task => { ContinueReplayWith(tmOriginal, TestParams); });
            } catch (Exception exc) { Log = exc; }
        }
Ejemplo n.º 7
0
        public async Task <ActionResult <IEnumerable <MemberDto> > > GetTestFilter([FromQuery] TestParams filtrationParams)
        {
            var membersList = await _memberRepository.GetMembersTestFilterAsync(filtrationParams);

            Response.AddFiltrationHeader(membersList);

            return(membersList.Result);
        }
Ejemplo n.º 8
0
        public static void Init(string parametersFile)
        {
            TextReader reader = new StreamReader(parametersFile);

            XmlSerializer serializer = new XmlSerializer(typeof(TestParams));

            TestParams = (TestParams)serializer.Deserialize(reader);
        }
Ejemplo n.º 9
0
            internal static TestParams Create()
            {
                TestParams @params = new TestParams();
                //Properties props = System.GetProperties();
                IDictionary <string, string> props = new System.Collections.Generic.Dictionary <string, string>();

                @params.ParseProperties(props);
                return(@params);
            }
Ejemplo n.º 10
0
 public UsageContextGeneralTest(bool expectedCanUse, bool canUseItem, bool canUseItemWeapon)
 {
     Params = new TestParams()
     {
         CanUseItem       = canUseItem,
         ExpectedCanUse   = expectedCanUse,
         CanUseItemWeapon = canUseItemWeapon
     };
 }
Ejemplo n.º 11
0
        public void SetupPDF()
        {
            pdf = new Pdfium();
            TestParams filePath = LoadJson();
            string     file     = filePath.pathToFile;

            Console.WriteLine("\nOpen PDF file: " + file);

            pdf.LoadFile(file);
        }
Ejemplo n.º 12
0
        public static TestParams LoadJson()
        {
            string jsonPath = Environment.GetEnvironmentVariable("JsonFilePath") as string;

            using (StreamReader r = new StreamReader(jsonPath))
            {
                string     json  = r.ReadToEnd();
                TestParams param = JsonConvert.DeserializeObject <TestParams>(json);
                return(param);
            }
        }
Ejemplo n.º 13
0
            public ClientTest(TestParams paramin)
            {
                param     = paramin;
                transport = param.CreateTransport();
                TProtocol protocol = param.CreateProtocol(transport);

                if (param.multiplexed)
                {
                    second = new SecondService.Client(new TMultiplexedProtocol(protocol, "SecondService"));
                }
                client        = new ThriftTest.Client(protocol);
                numIterations = param.numIterations;
            }
Ejemplo n.º 14
0
        private GameValue Solve(TestParams testParams, bool visualize, ConfigureSolver configureSolver)
        {
            if (visualize)
            {
                VisActionTree.Show(testParams.ActionTree,
                                   Path.Combine(_outDir, String.Format("{0}-at.gv", testParams.Name)));
                VisChanceTree.Show(testParams.ChanceTree,
                                   Path.Combine(_outDir, String.Format("{0}-ct.gv", testParams.Name)));
                for (int p = 0; p < testParams.StrategyTrees.Length; ++p)
                {
                    VisStrategyTree.Show(testParams.StrategyTrees[p],
                                         Path.Combine(_outDir, string.Format("{0}-st-{1}.gv", testParams.Name, p)));
                }
            }

            // Make sure input is correct.
            for (int p = 0; p < testParams.ChanceTree.Nodes[0].Position; ++p)
            {
                string errorText;
                Assert.IsTrue(VerifyAbsStrategy.Verify(testParams.StrategyTrees[p], p, 0.000001, out errorText), errorText);
            }

            GameValue gv = new GameValue {
                ChanceTree = testParams.ChanceTree, ActionTree = testParams.ActionTree, Strategies = testParams.StrategyTrees
            };

            gv.PrepareVis = visualize;

            if (configureSolver != null)
            {
                configureSolver(gv);
            }

            gv.Solve();

            if (visualize)
            {
                for (int p = 0; p < testParams.ChanceTree.PlayersCount; ++p)
                {
                    GameValue.Vis.Show(gv, p, Path.Combine(_outDir, String.Format("{0}-{1}-val.gv", testParams.Name, p)));
                }
            }

            Assert.AreEqual(2, gv.Values.Length);
            for (int p = 0; p < testParams.ChanceTree.PlayersCount; ++p)
            {
                Console.WriteLine("Game value pos {0}: {1}", p, gv.Values[p]);
                Assert.AreEqual(testParams.ExpectedResult[p], gv.Values[p], testParams.Epsilon);
            }
            return(gv);
        }
Ejemplo n.º 15
0
 private static void PrintDiskUtilization(TestParams options)
 {
     if (options.CacheOptions.PhysicalCacheDir == options.MetaStoreOptions.DatabaseDir)
     {
         PrintDiskUtilization("Cache", options.MetaStoreOptions.DatabaseDir,
                              options.CacheOptions.CleanupManagerOptions.MaxCacheBytes);
     }
     else
     {
         PrintDiskUtilization("Files", options.CacheOptions.PhysicalCacheDir,
                              options.CacheOptions.CleanupManagerOptions.MaxCacheBytes);
         PrintDiskUtilization("Database", options.MetaStoreOptions.DatabaseDir,
                              options.CacheOptions.CleanupManagerOptions.MaxCacheBytes);
     }
 }
        public void GetAllDoesNotRemoveDeletedItems(TestParams testParams)
        {
            var wrapper = MakeWrapper(testParams);
            var itemA   = new TestItem("itemA");

            _core.ForceSet(TestDataKind, "keyA", 1, itemA);
            _core.ForceSet(TestDataKind, "keyB", 2, null); // deleted item

            var items    = wrapper.GetAll(TestDataKind).Items.ToDictionary(kv => kv.Key, kv => kv.Value);
            var expected = ImmutableDictionary.Create <string, ItemDescriptor>()
                           .Add("keyA", itemA.WithVersion(1))
                           .Add("keyB", ItemDescriptor.Deleted(2));

            Assert.Equal(expected, items);
        }
Ejemplo n.º 17
0
        public void Test_Kuhn()
        {
            TestParams testParams = new TestParams(this, "kuhn.gamedef.xml", null, /* new KuhnChanceAbstraction(),*/ 0.001);

            SolveAndVerifyVerifySolution(testParams, true, false,
                                         new int[] { -1 },
                                         s =>
            {
                s.IsVerbose           = true;
                s.EpsilonLogThreshold = 0;
                s.IterationVerbosity  = 1000;
                s.MaxIterationCount   = 0;
                s.ThreadsCount        = 0; // Test single-threaded variant.
            });
        }
        public void GetDeletedItem(TestParams testParams)
        {
            var wrapper = MakeWrapper(testParams);
            var key     = "flag";
            var itemv2  = new TestItem("itemv2");

            _core.ForceSet(TestDataKind, key, 1, null);
            Assert.Equal(new ItemDescriptor(1, null), wrapper.Get(TestDataKind, key));

            _core.ForceSet(TestDataKind, key, 2, itemv2);
            var result = wrapper.Get(TestDataKind, key);

            // if cached, we will not see the new underlying value yet
            Assert.Equal(testParams.CacheMode.IsUncached ? itemv2.WithVersion(2) : ItemDescriptor.Deleted(1), result);
        }
Ejemplo n.º 19
0
        private void Solve(TestParams testParams, bool visualize, ConfigureSolver configureSolver)
        {
            if (visualize)
            {
                VisActionTree.Show(testParams.ActionTree,
                                   Path.Combine(_outDir, String.Format("{0}-at.gv", testParams.Name)));
                VisChanceTree.Show(testParams.ChanceTree,
                                   Path.Combine(_outDir, String.Format("{0}-ct.gv", testParams.Name)));
            }

            StrategyTree [] eqStrategies = new StrategyTree[testParams.ChanceTree.PlayersCount];

            string error;

            for (int heroPos = 0; heroPos < testParams.ChanceTree.PlayersCount; ++heroPos)
            {
                // Create and configure EqLp solver
                EqLp solver = new EqLp
                {
                    HeroPosition = heroPos,
                    ChanceTree   = testParams.ChanceTree,
                    ActionTree   = testParams.ActionTree,
                };

                if (configureSolver != null)
                {
                    configureSolver(solver);
                }

                // Solve EqLp
                solver.Solve();
                eqStrategies[heroPos] = solver.Strategy;

                if (visualize)
                {
                    VisStrategyTree.Show(solver.Strategy,
                                         Path.Combine(_outDir, string.Format("{0}-eq-{1}.gv", testParams.Name, heroPos)));
                }

                // Verify the eq value and strategy
                Assert.AreEqual(testParams.ExpectedResult[heroPos], solver.Value, testParams.Epsilon, "Wrong eq value");
                Assert.IsTrue(VerifyAbsStrategy.Verify(solver.Strategy, solver.HeroPosition, 1e-7, out error), error);
            }
            // Verify eq, use another (better) epsilon because EqLp and VerifyEq have better precision
            // than most of the reference game solvers like OCFR.
            Assert.IsTrue(VerifyEq.Verify(testParams.ActionTree, testParams.ChanceTree, eqStrategies, 1e-7, out error), error);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Solves the game by fictitious play and verifies the solution.
        /// </summary>
        /// <param name="snapshotAfter">Number of iterations to make an intermediate snapshot after. -1 for no intermediate snapshot.</param>
        /// <param name="configureSolver"></param>
        private void SolveAndVerifyVerifySolution(TestParams testParams, bool visualize, bool trace, int[] iterCounts, ConfigureSolver configureSolver)
        {
            int playersCount = testParams.ChanceTree.PlayersCount;

            StrategyTree eqStrategy = RunSolver(testParams, visualize, trace, iterCounts, configureSolver);
            string       error;

            // Verify consistency of strategies
            for (int p = 0; p < 2; ++p)
            {
                Assert.IsTrue(VerifyAbsStrategy.Verify(eqStrategy, p, 1e-7, out error), string.Format("Pos {0}: {1}", p, error));
            }

            // Run VerifyEq on the computed strategies.
            StrategyTree[] strategies = new StrategyTree[] { eqStrategy, eqStrategy };
            Assert.IsTrue(VerifyEq.Verify(testParams.ActionTree, testParams.ChanceTree,
                                          strategies, 3 * testParams.Epsilon, out error), error);

            //
            // Do a redundant test with EqLp
            //

            // Find game values for our solution
            GameValue gv = new GameValue
            {
                ActionTree = testParams.ActionTree,
                ChanceTree = testParams.ChanceTree,
                Strategies = new StrategyTree[] { eqStrategy, eqStrategy }
            };

            gv.Solve();

            // Solve eq with EqLp
            double[]       expEqValues;
            StrategyTree[] expStrategies = EqLp.Solve(testParams.ActionTree, testParams.ChanceTree, out expEqValues);

            // Verify the eq value and strategy
            for (int p = 0; p < 2; ++p)
            {
                if (visualize)
                {
                    Console.WriteLine("Expected eq value pos {0}: {1}", p, expEqValues[p]);
                }
                Assert.AreEqual(expEqValues[p], gv.Values[p], testParams.Epsilon, "Eq value differs from EqLp solution");
            }
        }
Ejemplo n.º 21
0
        public static int Execute(List <string> args)
        {
            try
            {
                var param = new TestParams();

                try
                {
                    param.Parse(args);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("*** FAILED ***");
                    Console.WriteLine("Error while  parsing arguments");
                    Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
                    return(ErrorUnknown);
                }

                var tests = Enumerable.Range(0, param.numThreads).Select(_ => new ClientTest(param)).ToArray();

                //issue tests on separate threads simultaneously
                var threads = tests.Select(test => new Thread(test.Execute)).ToArray();
                var start   = DateTime.Now;
                foreach (var t in threads)
                {
                    t.Start();
                }

                foreach (var t in threads)
                {
                    t.Join();
                }

                Console.WriteLine("Total time: " + (DateTime.Now - start));
                Console.WriteLine();
                return(tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2));
            }
            catch (Exception outerEx)
            {
                Console.WriteLine("*** FAILED ***");
                Console.WriteLine("Unexpected error");
                Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
                return(ErrorUnknown);
            }
        }
Ejemplo n.º 22
0
        public static TestParams LoadJson()
        {
            //dotnet test の場合
            string jsonPath = Environment.GetEnvironmentVariable("JsonFilePath");

            //dotnet vstest の場合
            if (jsonPath == null)
            {
                jsonPath = "C:/Users/KINU04/Desktop/AllAckahProjs_2019/FreshStartMorisawa/testparams.json";
            }

            using (StreamReader r = new StreamReader(jsonPath))
            {
                string     json  = r.ReadToEnd();
                TestParams param = JsonConvert.DeserializeObject <TestParams>(json);
                return(param);
            }
        }
Ejemplo n.º 23
0
        private static async Task TestAsyncMediumLimitedCacheWavesMetaStore(CancellationToken cancellationToken)
        {
            var options = new TestParams()
            {
                CacheOptions = new HybridCacheOptions(null)
                {
                    Subfolders        = 2048,
                    AsyncCacheOptions = new AsyncCacheOptions()
                    {
                        MaxQueuedBytes = 100 * 100 * 1000,
                        FailRequestsOnEnqueueLockTimeout = true,
                        WriteSynchronouslyWhenQueueFull  = true,
                        MoveFileOverwriteFunc            = (from, to) => File.Move(from, to, true),
                        MoveFilesIntoPlace = false
                    },
                    CleanupManagerOptions = new CleanupManagerOptions()
                    {
                        MaxCacheBytes   = 409600000, // 1/2th the size of the files we are trying to write
                        MinAgeToDelete  = TimeSpan.Zero,
                        MinCleanupBytes = 0,
                    },
                },
                MetaStoreOptions = new MetaStoreOptions(null)
                {
                    Shards = 32
                },
                UseMetaStore             = true,
                FileSize                 = 81920,
                FileCount                = 10000,
                RequestCountPerWave      = 1000,
                RequestWaves             = 10,
                RebootCount              = 12,
                RequestWavesIntermission = TimeSpan.FromMilliseconds(15),
                CreationTaskDelay        = TimeSpan.FromMilliseconds(0),
                CreationThreadSleep      = TimeSpan.FromMilliseconds(0),
                DisplayLog               = false,
                Synchronous              = false,
                MaxLogEntries            = 75,
                WaitForKeypress          = true,
            };

            Console.WriteLine("Starting HybridCache test with the async queue disabled and the cache limited to 1/5th the needed size");
            await TestRandom(options, cancellationToken);
        }
Ejemplo n.º 24
0
        private void Submit_Click(object sender, EventArgs e)
        {
            if (this.Entity == null)
            {
                this.Entity    = new TestParams();
                this.Entity.Id = Guid.NewGuid().ToString();
            }
            this.Entity.Name      = this.textBox1.Text.Trim();
            this.Entity.Desc      = this.textBox2.Text.Trim();
            this.Entity.ParamList = (List <TestParam>) this.myGridView1.DataSource;
            if (isModify)
            {
                bll.SelectAll().RemoveAll(p => p.Id == this.Entity.Id);
            }

            bll.Dao.Save(this.Entity);
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }
Ejemplo n.º 25
0
        protected TestParams GetParams()
        {
            var result = new TestParams();
            var row    = TestContext.DataRow;

            if (row != null)
            {
                foreach (DataColumn column in row.Table.Columns)
                {
                    var key      = column.ColumnName.Split(new[] { "__" }, StringSplitOptions.RemoveEmptyEntries);
                    var objValue = row[column.ColumnName];
                    var value    = objValue is DBNull ? null : (string)objValue;
                    if (key.Length == 1)
                    {
                        if (key[0] == "Pattern")
                        {
                            result.Pattern = value;
                        }
                        else if (key[0] == "Url")
                        {
                            result.Url = value;
                        }
                        else if (key[0] == "Result")
                        {
                            result.Result = bool.Parse(value);
                        }
                        else
                        {
                            result.RouteValues[key[0]] = value;
                        }
                    }
                    else if (key[0] == "default")
                    {
                        result.Defaults[key[1]] = value;
                    }
                    else if (key[0] == "constraint")
                    {
                        result.Constraints[key[1]] = value;
                    }
                }
            }
            return(result);
        }
        public void BuildRequestParamsHandlesBasicObject()
        {
            var subject = new RestSharpRequestHandler("xxx");
            var testParams = new TestParams
            {
                MyString = "foo",
                MyBool = true,
                MyBytes = new byte[10],
                MyEnum = TestEnumParams.TestItem2,
                MyInt = 90
            };

            var result = subject.BuildRequestParams(testParams);

            Assert.Equal(4, result.Keys.Count);
            Assert.Equal("foo", result["my_string"]);
            Assert.Equal("true", result["my_bool"]);
            Assert.Equal("test_item2", result["my_enum"]);
            Assert.Equal("90", result["my_int"]);
        }
        public void TestBatch()
        {
            var param1 = new TestParams
            {
                Param2 = "abc",
                Param1 = 114514
            };
            var param2 = new TestParams
            {
                Param2 = "def",
                Param1 = 1919810
            };
            var batch = new RpcBatchParams <bool>(param1, param2)
            {
                Token = "token"
            };

            TestSerialization(batch,
                              "[\"token\",[{\"methodName\":\"test.testMethod\",\"params\":[\"abc\",114514]},{\"methodName\":\"test.testMethod\",\"params\":[\"def\",1919810]}]]");
        }
Ejemplo n.º 28
0
        private Modifier GetTestModifier(TestParams testParams)
        {
            switch (testParams.Grade)
            {
            case EGrades.One:
                return(new LevelOne().Modifier);

            case EGrades.Two:
                return(new LevelTwo().Modifier);

            case EGrades.Three:
                return(new LevelThree().Modifier);

            case EGrades.Four:
                return(new LevelFour().Modifier);

            default:
                return(new LevelOne().Modifier);
            }
        }
        public void GetMissingItem(TestParams testParams)
        {
            var wrapper = MakeWrapper(testParams);
            var key     = "flag";
            var item    = new TestItem("item");

            Assert.Null(wrapper.Get(TestDataKind, key));

            _core.ForceSet(TestDataKind, key, 1, item);
            var result = wrapper.Get(TestDataKind, key);

            if (testParams.CacheMode.IsCached)
            {
                Assert.Null(result); // the cache can retain a null result
            }
            else
            {
                Assert.Equal(item.WithVersion(1), result);
            }
        }
        public void BuildRequestParamsHandlesBasicObject()
        {
            var subject    = new RestSharpRequestHandler("xxx");
            var testParams = new TestParams
            {
                MyString = "foo",
                MyBool   = true,
                MyBytes  = new byte[10],
                MyEnum   = TestEnumParams.TestItem2,
                MyInt    = 90
            };

            var result = subject.BuildRequestParams(testParams);

            Assert.Equal(4, result.Keys.Count);
            Assert.Equal("foo", result["my_string"]);
            Assert.Equal("true", result["my_bool"]);
            Assert.Equal("test_item2", result["my_enum"]);
            Assert.Equal("90", result["my_int"]);
        }
Ejemplo n.º 31
0
        public static int Execute(string[] args)
        {
            try
            {
                TestParams param      = new TestParams();
                int        numThreads = 1;
                try
                {
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i] == "-u")
                        {
                            param.url = args[++i];
                        }
                        else if (args[i] == "-n")
                        {
                            param.numIterations = Convert.ToInt32(args[++i]);
                        }
                        else if (args[i] == "-pipe")  // -pipe <name>
                        {
                            param.pipe = args[++i];
                            Console.WriteLine("Using named pipes transport");
                        }
                        else if (args[i].Contains("--host="))
                        {
                            param.host = args[i].Substring(args[i].IndexOf("=") + 1);
                        }
                        else if (args[i].Contains("--port="))
                        {
                            param.port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
                        }
                        else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
                        {
                            param.buffered = true;
                            Console.WriteLine("Using buffered sockets");
                        }
                        else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
                        {
                            param.framed = true;
                            Console.WriteLine("Using framed transport");
                        }
                        else if (args[i] == "-t")
                        {
                            numThreads = Convert.ToInt32(args[++i]);
                        }
                        else if (args[i] == "--compact" || args[i] == "--protocol=compact")
                        {
                            param.protocol = "compact";
                            Console.WriteLine("Using compact protocol");
                        }
                        else if (args[i] == "--json" || args[i] == "--protocol=json")
                        {
                            param.protocol = "json";
                            Console.WriteLine("Using JSON protocol");
                        }
                        else if (args[i] == "--ssl")
                        {
                            param.encrypted = true;
                            Console.WriteLine("Using encrypted transport");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("*** FAILED ***");
                    Console.WriteLine("Error while  parsing arguments");
                    Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
                    return(ErrorUnknown);
                }

                var tests = Enumerable.Range(0, numThreads).Select(_ => new ClientTest(param)).ToArray();
                //issue tests on separate threads simultaneously
                var      threads = tests.Select(test => new Thread(test.Execute)).ToArray();
                DateTime start   = DateTime.Now;
                foreach (var t in threads)
                {
                    t.Start();
                }
                foreach (var t in threads)
                {
                    t.Join();
                }
                Console.WriteLine("Total time: " + (DateTime.Now - start));
                Console.WriteLine();
                return(tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2));
            }
            catch (Exception outerEx)
            {
                Console.WriteLine("*** FAILED ***");
                Console.WriteLine("Unexpected error");
                Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
                return(ErrorUnknown);
            }
        }
Ejemplo n.º 32
0
 public ClientTest(TestParams param)
 {
     transport     = param.CreateTransport();
     client        = new ThriftTest.Client(param.CreateProtocol(transport));
     numIterations = param.numIterations;
 }
        public void BuildRequestParamsHandlesComplexObject()
        {
            var complexObject = new TestParams
            {
                MyString = "inner-foo"
            };

            var mockParser = new Mock<IResponseParser>();

            mockParser.Setup(p => p.SerializeMessage(complexObject))
                      .Returns("{\"json\": \"result\"}")
                      .Verifiable();

            var subject = new RestSharpRequestHandler("xxx");
            subject.ResponseParser = mockParser.Object;

            var testParams = new TestParams
            {
                MyInt = 90,
                MyComplexObject = complexObject
            };

            var result = subject.BuildRequestParams(testParams);

            Assert.Equal(2, result.Keys.Count);
            Assert.Equal("{\"json\": \"result\"}", result["my_complex_object"]);
            Assert.Equal("90", result["my_int"]);

            mockParser.Verify();
        }
Ejemplo n.º 34
0
        public static int Execute(List<string> args)
        {
            try
            {
                var param = new TestParams();

                try
                {
                    param.Parse(args);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("*** FAILED ***");
                    Console.WriteLine("Error while  parsing arguments");
                    Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
                    return ErrorUnknown;
                }

                var tests = Enumerable.Range(0, param.numThreads).Select(_ => new ClientTest(param)).ToArray();

                //issue tests on separate threads simultaneously
                var threads = tests.Select(test => new Thread(test.Execute)).ToArray();
                var start = DateTime.Now;
                foreach (var t in threads)
                {
                    t.Start();
                }

                foreach (var t in threads)
                {
                    t.Join();
                }

                Console.WriteLine("Total time: " + (DateTime.Now - start));
                Console.WriteLine();
                return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2);
            }
            catch (Exception outerEx)
            {
                Console.WriteLine("*** FAILED ***");
                Console.WriteLine("Unexpected error");
                Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
                return ErrorUnknown;
            }
        }
Ejemplo n.º 35
0
        public static int Execute(string[] args)
        {
            try
            {
                TestParams param = new TestParams();
                int numThreads = 1;
                try
                {
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i] == "-u")
                        {
                            param.url = args[++i];
                        }
                        else if (args[i] == "-n")
                        {
                            param.numIterations = Convert.ToInt32(args[++i]);
                        }
                        else if (args[i] == "-pipe")  // -pipe <name>
                        {
                            param.pipe = args[++i];
                            Console.WriteLine("Using named pipes transport");
                        }
                        else if (args[i].Contains("--host="))
                        {
                            param.host = args[i].Substring(args[i].IndexOf("=") + 1);
                        }
                        else if (args[i].Contains("--port="))
                        {
                            param.port = int.Parse(args[i].Substring(args[i].IndexOf("=")+1));
                        }
                        else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
                        {
                            param.buffered = true;
                            Console.WriteLine("Using buffered sockets");
                        }
                        else if (args[i] == "-f" || args[i] == "--framed"  || args[i] == "--transport=framed")
                        {
                            param.framed = true;
                            Console.WriteLine("Using framed transport");
                        }
                        else if (args[i] == "-t")
                        {
                            numThreads = Convert.ToInt32(args[++i]);
                        }
                        else if (args[i] == "--compact" || args[i] == "--protocol=compact")
                        {
                            param.protocol = "compact";
                            Console.WriteLine("Using compact protocol");
                        }
                        else if (args[i] == "--json" || args[i] == "--protocol=json")
                        {
                            param.protocol = "json";
                            Console.WriteLine("Using JSON protocol");
                        }
                        else if (args[i] == "--ssl")
                        {
                            param.encrypted = true;
                            Console.WriteLine("Using encrypted transport");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("*** FAILED ***");
                    Console.WriteLine("Error while  parsing arguments");
                    Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
                    return ErrorUnknown;
                }

                var tests = Enumerable.Range(0, numThreads).Select(_ => new ClientTest(param)).ToArray();
                //issue tests on separate threads simultaneously
                var threads = tests.Select(test => new Thread(test.Execute)).ToArray();
                DateTime start = DateTime.Now;
                foreach (var t in threads)
                    t.Start();
                foreach (var t in threads)
                    t.Join();
                Console.WriteLine("Total time: " + (DateTime.Now - start));
                Console.WriteLine();
                return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2);
            }
            catch (Exception outerEx)
            {
                Console.WriteLine("*** FAILED ***");
                Console.WriteLine("Unexpected error");
                Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
                return ErrorUnknown;
            }
        }
Ejemplo n.º 36
0
 public ClientTest(TestParams param)
 {
     transport = param.CreateTransport();
     client = new ThriftTest.Client(param.CreateProtocol(transport));
     numIterations = param.numIterations;
 }