Beispiel #1
0
        void ShouldCompressAndDecompress(IRunner runner, string streamName)
        {
            var inputFileName    = WriteStreamToTempFile(streamName);
            var compressedFile   = Path.GetTempFileName();
            var decompressedFile = Path.GetTempFileName();

            try
            {
                Options.TryParse(new[] { "compress", inputFileName, compressedFile }, Console.Out, out Options options).Should().BeTrue();
                runner.Run(options);

                Options.TryParse(new[] { "decompress", compressedFile, decompressedFile }, Console.Out, out Options options2).Should().BeTrue();
                runner.Run(options2);

                var inputBytes        = File.ReadAllBytes(inputFileName);
                var decompressedBytes = File.ReadAllBytes(decompressedFile);

                CollectionAssert.AreEqual(inputBytes, decompressedBytes);
            }
            finally
            {
                DeleteFileIfExists(inputFileName);
                DeleteFileIfExists(compressedFile);
                DeleteFileIfExists(decompressedFile);
            }
        }
Beispiel #2
0
        public async void SimpleFetchMultipleCriteriaTest(IRunner runner)
        {
            var inp = new SomeEntity {
                AnInt   = 5,
                AString = "foo"
            };

            await runner.Run(_logger, async db => {
                await db.InsertAsync(inp);

                var outp = await db.FetchAsync <SomeEntity>(
                    Translator.ConjunctionWord.Or,
                    x => x.AString == "foo2",
                    x => x.AString == "foo");
                Assert.Equal(new List <SomeEntity> {
                    inp
                }, outp);
            });

            await runner.Run(_logger, async db => {
                await db.InsertAsync(inp);

                var outp = await db.FetchAsync <SomeEntity>(
                    Translator.ConjunctionWord.And,
                    x => x.AString == "foo",
                    x => x.AnInt == 5);
                Assert.Equal(new List <SomeEntity> {
                    inp
                }, outp);
            });
        }
Beispiel #3
0
        private static FeatureResults Run(NBehaveConfiguration config)
        {
            IRunner        runner         = config.Build();
            FeatureResults featureResults = runner.Run();

            return(featureResults);
        }
Beispiel #4
0
        static async Task Main(string[] args)
        {
            ServiceProvider serviceProvider = BuildServiceProvider();

            IRunner runner = serviceProvider.GetService <IRunner>();
            await runner.Run(CancellationToken.None);
        }
Beispiel #5
0
        private void QueueStrategy(IRunner runner, string strategyPath, CancellationToken cancellationToken)
        {
            var ts  = TaskScheduler.Default;
            var tco = TaskCreationOptions.LongRunning;

            Task.Factory.StartNew(() => runner.Run(strategyPath), cancellationToken, tco, ts);
        }
Beispiel #6
0
 public async void FetchNothingWorksTest(IRunner runner)
 {
     await runner.Run(_logger, async db => {
         var outp = await db.FetchAsync <SomeEntity>(x => x.AString == "foo");
         Assert.Equal(new List <SomeEntity>(), outp);
     });
 }
Beispiel #7
0
 public CmdDslTests()
 {
     _runner = Substitute.For <IRunner>();
     _runner.Run(Arg.Any <IRunOptions>()).Returns("result");
     _runner.GetCommand().Returns(new Commando(_runner));
     cmd = new Cmd(_runner);
 }
Beispiel #8
0
        protected T Parse <T>(IRunner runner, string data) where T : class
        {
            var captures = new List <Capture>();
            var result   = runner.Run(data, captures);

            if (result.IsSuccessful)
            {
                var iterator = new CaptureIterator <Expression>(data, captures);
                var output   = BuildTree(iterator);
                if (output as T == null)
                {
                    throw new PegParsingException($"Unable to parse PEG: {output}");
                }

                return(output as T);
            }
            else
            {
                var near = data.Substring(result.InputPosition);
                if (near.Length > 10)
                {
                    near = near.Substring(0, 10);
                }

                throw new PegParsingException($"Parsing error at character {result.InputPosition}. {runner.ExplainResult(result, data)} near {near}");
            }
        }
        /// <summary>
        /// Determines which analyzers to run, which rule sets to use (TODO)
        /// and invokes the runners.
        /// </summary>
        static IEnumerable <IViolation> RunAnalyzers(DotNetProject project, double work)
        {
            string dll = project.GetOutputFileName(ConfigurationSelector.Default);

            if (!File.Exists(dll))
            {
                yield break;
            }

            LoadAnalyzersIfNeccessary();

            if (analyzers.Count == 0)
            {
                yield break;
            }

            double analyzerWork = work / analyzers.Count;

            foreach (IAnalyzer analyzer in analyzers)
            {
                IEnumerable <IRule> ruleSet = GetRuleSet(project, analyzer.GetRuleLoader());
                IRunner             runner  = analyzer.GetRunner();

                IEnumerable <IViolation> violations = runner.Run(dll, ruleSet);
                foreach (IViolation vio in violations)
                {
                    yield return(vio);
                }

                ResultsReporter.WorkComplete += analyzerWork;
            }
        }
 public void Should_run_scenario()
 {
     var result = _runner.Run();
     Assert.That(result.NumberOfFailingScenarios, Is.EqualTo(0));
     Assert.That(result.NumberOfPendingScenarios, Is.EqualTo(0));
     Assert.That(result.NumberOfPassingScenarios, Is.EqualTo(1));
 }
Beispiel #11
0
        public IActionResult Check(DescTraceTableViewModel viewModel)
        {
            viewModel.Row = viewModel.Row.Where(x => !string.IsNullOrEmpty(x)).ToList();

            var answer = _runner.Run(viewModel.SourceCodeForCheck);

            answer = answer.Replace("\r\n", " ").Trim();

            var userResult = string.Join(" ", viewModel.Row.Skip(viewModel.Variables.Count)).Trim();

            var result = TestResults.WA;

            if (answer == userResult)
            {
                result = TestResults.Ok;
            }

            Guid.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), out var userId);

            var solution = new Solution
            {
                Result    = result,
                UserId    = userId,
                Input     = userResult,
                ProblemId = viewModel.Id,
                SendTime  = DateTime.Now
            };

            _solutionsService.Save(solution);

            return(RedirectToAction("Description", "Problems", new { viewModel.Id }));
        }
        public IActionResult Check(DescCodeCorrectorViewModel viewModel)
        {
            var generator = _generators[viewModel.GeneratorType];
            var input     = generator.CreateData();

            try
            {
                var problemId = viewModel.Id;
                Guid.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), out var userId);

                var outPutRight = _runner.Run(viewModel.SourceCode, input).Trim('\n', '\r');
                var result      = TestResults.WA;
                var outPutUser  = "";
                try
                {
                    outPutUser = _runner.Run(viewModel.IncorrectSourceCode, input).Trim('\n', '\r');
                }
                catch
                {
                    result = TestResults.CE;
                }

                if (result != TestResults.CE && outPutRight == outPutUser)
                {
                    result = TestResults.Ok;
                }

                var solution = new Solution()
                {
                    Result    = result,
                    UserId    = userId,
                    Input     = viewModel.IncorrectSourceCode,
                    ProblemId = problemId,
                    SendTime  = DateTime.Now
                };
                _solutionsService.Save(solution);

                return(RedirectToAction("Description", "Problems", new { viewModel.Id }));
            }
            catch (Exception e)
            {
                return(View("Error", new ErrorViewModel()
                {
                    RequestId = e.Message
                }));
            }
        }
Beispiel #13
0
        public async void MultipleLinqConditions(IRunner runner)
        {
            var inp1 = new SomeEntity {
                AnInt = 5
            };
            var inp2 = new SomeEntity {
                AnInt = 6
            };
            var inp3 = new SomeEntity {
                AnInt = 7
            };
            var inp4 = new SomeEntity {
                AnInt = 8
            };
            var inp5 = new SomeEntity {
                AnInt = 9
            };

            await runner.Run(_logger, async db => {
                await db.InsertAsync(inp1);
                await db.InsertAsync(inp2);
                await db.InsertAsync(inp3);
                await db.InsertAsync(inp4);
                await db.InsertAsync(inp5);

                {
                    int?minVal = 6;
                    int?maxVal = 8;

                    var outp = await db.FetchAsync <SomeEntity>(Translator.ConjunctionWord.And,
                                                                x => !minVal.HasValue || x.AnInt >= minVal.Value,
                                                                x => !maxVal.HasValue || x.AnInt <= maxVal.Value);

                    Assert.Equal(new[] { 6, 7, 8 }, outp.Select(x => x.AnInt).OrderBy(x => x));
                }

                {
                    int?minVal = null;
                    int?maxVal = 8;

                    var outp = await db.FetchAsync <SomeEntity>(Translator.ConjunctionWord.And,
                                                                x => !minVal.HasValue || x.AnInt >= minVal.Value,
                                                                x => !maxVal.HasValue || x.AnInt <= maxVal.Value);

                    Assert.Equal(new[] { 5, 6, 7, 8 }, outp.Select(x => x.AnInt).OrderBy(x => x));
                }

                {
                    int?minVal = 7;
                    int?maxVal = null;

                    var outp = await db.FetchAsync <SomeEntity>(Translator.ConjunctionWord.And,
                                                                x => !minVal.HasValue || x.AnInt >= minVal.Value,
                                                                x => !maxVal.HasValue || x.AnInt <= maxVal.Value);

                    Assert.Equal(new[] { 7, 8, 9 }, outp.Select(x => x.AnInt).OrderBy(x => x));
                }
            });
        }
Beispiel #14
0
 private void RunScriptIfNotEmpty(IRunner scriptRunner, LightScript script)
 {
     if (script.Commands.Count() > 0)
     {
         RunnerFactory.PassDependencies(TestData);
         scriptRunner.Run(script);
     }
 }
        /// <summary>
        /// 根据模型定义参数执行存储过程进行查询,参数类型必须定义ReturnTypeAttribute特性
        /// </summary>
        /// <typeparam name="TPrarmType">存储过程参数类型</typeparam>
        /// <param name="runner">执行器</param>
        /// <param name="db">数据上下文</param>
        /// <param name="data">存储过程参数</param>
        /// <returns>返回类型枚举FalconSPReturnTypeAttribute定义的类型枚举。</returns>
        public static IEnumerable <object> Run <TPrarmType>(this IRunner runner, DbContext db, TPrarmType data)
        {
            var dType = typeof(TPrarmType);
            var attr  = dType.GetCustomAttribute <FalconSPReturnTypeAttribute>();

            if (attr != null && attr is FalconSPReturnTypeAttribute pna && pna.ReturnType != null)
            {
                return(runner.Run(db, dType, pna.ReturnType, data));
            }
Beispiel #16
0
        private async Task Run(RunContext runContext, IDictionary <string, object> variables)
        {
            using (new DirectorySwitch(fileSystemOperations, runContext.WorkingDirectory))
            {
                Message("Satisfying script requirements");
                await SatisfyRequirements(runContext.Script, variables);

                await runner.Run(runContext.Script, variables);
            }
        }
Beispiel #17
0
        private LockFile GetLockFile(string projectPath, string outputPath)
        {
            // Run the restore command
            string[] arguments = new[] { "restore", $"\"{projectPath}\"" };
            var      runStatus = runner.Run(Path.GetDirectoryName(projectPath), arguments);

            // Load the lock file
            string lockFilePath = Path.Combine(outputPath, "project.assets.json");

            return(LockFileUtilities.GetLockFile(lockFilePath, NuGet.Common.NullLogger.Instance));
        }
Beispiel #18
0
        public bool Run(BehindCodeItem compileCode, string callModuleName, ISysDesign callModule, object sender, object eventArgs, string actName, string actTag,
                        IBizDataItems sourceBizDatas, out IBizDataItems processBizDatas, bool isBuffer = true)
        {
            processBizDatas = null;

            if (_compilerObj == null)
            {
                _compilerObj = new Dictionary <string, IRunner>();
            }

            if (_isAllowDebug)
            {
                _compilerObj.Remove(compileCode.FuncName);
            }

            IRunner runner = null;

            if (_compilerObj.ContainsKey(compileCode.FuncName))
            {
                runner = _compilerObj[compileCode.FuncName];
            }
            else
            {
                runner = CompilerCode(compileCode);

                if (isBuffer && _isAllowDebug == false)
                {
                    //缓存编译对象
                    //调试状态不缓存编译对象
                    _compilerObj.Add(compileCode.FuncName, runner);
                }
            }

            if (runner != null)
            {
                IDBQuery thridDb = null;

                if (string.IsNullOrEmpty(compileCode.ThridDBAlias) == false)
                {
                    string strErr = "";
                    thridDb = SqlHelper.GetThridDBHelper(compileCode.ThridDBAlias, _dbHelper, ref strErr);
                    if (thridDb == null)
                    {
                        MessageBox.Show("动态方法 [" + compileCode.FuncName + "] 对应的数据源 [" + compileCode.ThridDBAlias + "] 链接对象创建失败," + strErr, "提示");
                        return(false);
                    }
                }

                runner.Init(_winRelateModules, _dbHelper, thridDb, _userData, _stationInfo, _dataTransCenter, _owiner);
                return(runner.Run(callModuleName, callModule, sender, eventArgs, actName, actTag, sourceBizDatas, out processBizDatas));
            }

            return(false);
        }
Beispiel #19
0
 private void Check(IRunner runner, ToMemoryCheckNotifier toMemory)
 {
     try
     {
         runner.Run(Activator.RepositoryLocator, new FromCheckNotifierToDataLoadEventListener(toMemory), toMemory, new GracefulCancellationToken());
     }
     catch (Exception e)
     {
         toMemory.OnCheckPerformed(new CheckEventArgs("Entire process crashed", CheckResult.Fail, e));
     }
 }
        public IActionResult Check(DescBlackBoxViewModel model)
        {
            var problemId = model.Id;

            Guid.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), out var userId);
            var result = TestResults.WA;

            var userCode    = model.Answer;
            var correctCode = model.SourceCode;

            var input = _generators[model.GeneratorType].CreateData();

            var outPutRight = _runner.Run(correctCode, input).Trim('\n', '\r');
            var outPutUser  = "";

            try
            {
                outPutUser = _runner.Run(userCode, input).Trim('\n', '\r');
            }
            catch
            {
                result = TestResults.CE;
            }

            if (result != TestResults.CE && outPutRight == outPutUser)
            {
                result = TestResults.Ok;
            }
            var solution = new Solution
            {
                Result    = result,
                UserId    = userId,
                Input     = userCode,
                ProblemId = problemId,
                SendTime  = DateTime.Now
            };

            _solutionsService.Save(solution);

            return(RedirectToAction("Description", "Problems", new { model.Id }));
        }
Beispiel #21
0
        public IList <TRunDetail> Execute()
        {
            var stopwatch        = Stopwatch.StartNew();
            var iterationResults = new List <TRunDetail>();

            do
            {
                var iterationStopwatch = Stopwatch.StartNew();

                // get next pipeline
                var getPipelineStopwatch = Stopwatch.StartNew();
                var pipeline             = PipelineSuggester.GetNextInferredPipeline(_context, _history, _datasetColumnInfo, _task,
                                                                                     _optimizingMetricInfo.IsMaximizing, _experimentSettings.CacheBeforeTrainer, _trainerAllowList);

                var pipelineInferenceTimeInSeconds = getPipelineStopwatch.Elapsed.TotalSeconds;

                // break if no candidates returned, means no valid pipeline available
                if (pipeline == null)
                {
                    break;
                }

                // evaluate pipeline
                _logger.Trace($"Evaluating pipeline {pipeline.ToString()}");
                (SuggestedPipelineRunDetail suggestedPipelineRunDetail, TRunDetail runDetail)
                    = _runner.Run(pipeline, _modelDirectory, _history.Count + 1);

                _history.Add(suggestedPipelineRunDetail);
                WriteIterationLog(pipeline, suggestedPipelineRunDetail, iterationStopwatch);

                runDetail.RuntimeInSeconds = iterationStopwatch.Elapsed.TotalSeconds;
                runDetail.PipelineInferenceTimeInSeconds = getPipelineStopwatch.Elapsed.TotalSeconds;

                ReportProgress(runDetail);
                iterationResults.Add(runDetail);

                // if model is perfect, break
                if (_metricsAgent.IsModelPerfect(suggestedPipelineRunDetail.Score))
                {
                    break;
                }

                // If after third run, all runs have failed so far, throw exception
                if (_history.Count() == 3 && _history.All(r => !r.RunSucceeded))
                {
                    throw new InvalidOperationException($"Training failed with the exception: {_history.Last().Exception}");
                }
            } while (_history.Count < _experimentSettings.MaxModels &&
                     !_experimentSettings.CancellationToken.IsCancellationRequested &&
                     stopwatch.Elapsed.TotalSeconds < _experimentSettings.MaxExperimentTimeInSeconds);

            return(iterationResults);
        }
Beispiel #22
0
 public async void SimpleInsertTest(IRunner runner)
 {
     var inp = new SomeEntity {
         AnInt   = 5,
         AString = "foo"
     };
     await runner.Run(_logger, async db => {
         await db.InsertAsync(inp);
         Assert.Equal(1, await db.ExecuteScalarAsync <int>("select count(*) from SomeEntity"));
         Assert.NotEqual(0, inp.Id);
     });
 }
Beispiel #23
0
            public void SetUp()
            {
                var scenarioText = "Feature: Config file support" + Environment.NewLine +
                                   "Scenario: Reading values from a config file" + Environment.NewLine +
                                   "Given an assembly with a matching configuration file" + Environment.NewLine +
                                   "When the value of setting foo is read" + Environment.NewLine +
                                   "Then the value should be meeble";

                SetupConfigFile();
                runner = CreateTextRunner(new[] { Path.Combine(GetAssemblyLocation(), "TestLib.dll") }, scenarioText);

                results = runner.Run();
            }
Beispiel #24
0
        protected async Task Run(string path, IDictionary <string, object> variables)
        {
            var script           = Compiler.Compile(path);
            var workingDirectory = Path.GetDirectoryName(path);

            using (new DirectorySwitch(FileSystemOperations, workingDirectory))
            {
                Message("Satisfying script requirements");
                await SatisfyRequirements(script, variables);

                await Runner.Run(script, variables);
            }
        }
            public void SetUp()
            {
                var scenarioText = "Feature: Config file support\r\n" +
                                    "Scenario: Reading values from a config file\r\n" +
                                    "Given an assembly with a matching configuration file\r\n" +
                                    "When the value of setting foo is read\r\n" +
                                    "Then the value should be meeble";
                SetupConfigFile();
                runner = CreateTextRunner(new[] { "TestPlainTextAssembly.dll" }, scenarioText);

                results = runner.Run();

            }
Beispiel #26
0
        public async void SimpleNotExistsTest(IRunner runner)
        {
            var inp = new SomeEntity {
                AnInt   = 5,
                AString = "foo1"
            };

            await runner.Run(_logger, async db => {
                await db.InsertAsync(inp);

                Assert.False(await db.ExistsAsync <SomeEntity>(x => x.AString == "foo"));
            });
        }
Beispiel #27
0
        public void ShouldRunTheCommandAgainstCmd()
        {
            IRunOptions expectedRunOptions = null;

            _runner.Run(Arg.Any <IRunOptions>())
            .ReturnsForAnyArgs("")
            .AndDoes(info => expectedRunOptions = info.Arg <IRunOptions>());

            cmd.dir();

            Assert.Equal("cmd", expectedRunOptions.Command);
            Assert.Equal("/c dir", expectedRunOptions.Arguments);
        }
Beispiel #28
0
        public void ShouldBeAbleToGetOutputFromCommand()
        {
            _runner.Run(Arg.Any <IRunOptions>()).Returns("out");

            var output = cmd.git();

            Assert.Equal(output, "out");
        }
Beispiel #29
0
        public async void IsNullSingleTest(IRunner runner)
        {
            var inp = new SomeEntity {
                AnInt   = 5,
                AString = "foo"
            };

            await runner.Run(_logger, async db => {
                await db.InsertAsync(inp);

                var outp = await db.SingleAsync <SomeEntity>(x => x.NullableInt == null);
                Assert.Equal(inp, outp);
            });
        }
Beispiel #30
0
        public int CompareTo(IRunner runner)
        {
            float time1 = this.Run(100);
            float time2 = runner.Run(100);

            if (time1 > time2)
            {
                return(1);
            }
            else if (time1 < time2)
            {
                return(-1);
            }
            return(0);
        }
        protected override void Because()
        {
            base.Because();

            var statLightConfigurationFactory = new StatLightConfigurationFactory(_testLogger);

            var statLightConfiguration = statLightConfigurationFactory.GetStatLightConfigurationForXap(
                ClientTestRunConfiguration.UnitTestProviderType,
                _pathToIntegrationTestXap,
                MSTestVersion,
                ClientTestRunConfiguration.MethodsToTest,
                ClientTestRunConfiguration.TagFilter,
                1,
                false,
                "", StatLight.Core.WebBrowser.WebBrowserType.SelfHosted,
                forceBrowserStart:true,
                showTestingBrowserHost:false);

            //bool showTestingBrowserHost = statLightConfiguration.Server.XapHostType == XapHostType.MSTestApril2010;
            _testLogger.Debug("Setting up xaphost {0}".FormatWith(statLightConfiguration.Server.XapHostType));
            Runner = _statLightRunnerFactory.CreateOnetimeConsoleRunner(statLightConfiguration);

            TestReport = Runner.Run();
        }
            public void SetUp()
            {
                var writer = new XmlTextWriter(new MemoryStream(), Encoding.UTF8);
                var listener = new XmlOutputEventListener(writer);

                const string scenarioText = "Feature: " + FeatureTitle + "\r\n" +
                                            "Scenario: Reading values from a config file\r\n" +
                                            "Given an assembly with a matching configuration file\r\n" +
                                            "When the value of setting foo is read\r\n" +
                                            "Then the value should be bar";

                SetupConfigFile();
                runner = CreateTextRunner(new[] { "TestPlainTextAssembly.dll" }, listener, scenarioText);

                results = runner.Run();

                xmlOut = new XmlDocument();
                writer.BaseStream.Seek(0, SeekOrigin.Begin);
                xmlOut.Load(writer.BaseStream);
            }
            public void SetUp()
            {
                var scenarioText = "Feature: Config file support\r\n" +
                                    "Scenario: Reading values from a config file\r\n" +
                                    "Given an assembly with a matching configuration file\r\n" +
                                    "When the value of setting foo is read\r\n" +
                                    "Then the value should be bar";
                SetupConfigFile();
                runner = CreateTextRunner(new[] { "TestPlainTextAssembly.dll" }, scenarioText);

                results = runner.Run();
            }
Beispiel #34
0
		private Task Start(IRunner runner)
		{
			return Task.Run(() => runner.Run(_tokenSource), CancellationToken.None);
		}