public void OnAfterTestListCompleted(RunResult result)
        {
            try {
                string path = resultsPath + "\\ConsolidatedReport.xml";
                string passedCount = result.PassedCount.ToString();
                string failedCount = result.FailedCount.ToString();
                string notRunCount = result.NotRunCount.ToString();
                string totalCount = result.AllCount.ToString();
                string runTime = (result.EndTime - result.StartTime).ToString();

                XmlTextWriter textWriter = new XmlTextWriter(path, null);
                textWriter.WriteStartDocument();
                textWriter.WriteStartElement("testsuites");
                textWriter.WriteStartElement("testsuite");
                textWriter.WriteAttributeString("name", listName);
                textWriter.WriteAttributeString("tests", totalCount.ToString());
                textWriter.WriteAttributeString("failures", failedCount.ToString());
                textWriter.WriteAttributeString("skipped", notRunCount.ToString());
                textWriter.WriteAttributeString("time", runTime);

                List<TestResult> list = result.TestResults;

                foreach (TestResult test in list)
                {
                    string testName = test.TestName;
                    string duration = test.Duration.Minutes.ToString() + " min " + test.Duration.Seconds.ToString() + " sec";
                    string testResult = test.Result.ToString().ToUpper();
                    string testLog = test.Message.ToString();

                    textWriter.WriteStartElement("testcase");
                    textWriter.WriteAttributeString("classname", testName);
                    textWriter.WriteAttributeString("name", testName);
                    textWriter.WriteAttributeString("time", test.Duration.ToString());
                    if (test.Result.ToString().Equals("Fail"))
                    {
                        textWriter.WriteStartElement("failure");
                        textWriter.WriteAttributeString("message", "FAILED");
                        textWriter.WriteEndElement();
                        textWriter.WriteElementString("system-out", testLog);
                    }
                    textWriter.WriteEndElement();
                }

                textWriter.WriteEndElement();
                textWriter.WriteEndElement();
                textWriter.WriteEndDocument();
                textWriter.Close();
            }
            catch (Exception ex)
            {
                Manager.Current.Log.WriteLine(ex.Message  + ex.Source + ex.StackTrace);
            }
        }
Ejemplo n.º 2
0
 internal void SetResult(RunResult runResult)
 {
     plasmaSlice = runResult.plasmaTotalSlice;
     buffySlice = runResult.buffySlice;
     plasmaVolume = runResult.plasmaVolume;
     buffyVolume = runResult.buffyVolume;
     int curSmpID = 1;
     foreach (var slice in runResult.plasmaRealSlices)
     {
         smpPlasmaSlices.Add(curSmpID++, slice);
     }
 }
 public static RunResult Run(RunOptions options)
 {
     RunResult result = new RunResult();
     using (Process p = Detach(options))
     {
         Thread.Sleep(2000);
         p.WaitForInputIdle();
         result.WindowTitle = p.MainWindowTitle;
         p.CloseMainWindow();
         p.WaitForExit();
         result.ExitCode = p.ExitCode;
     }
     return result;
 }
Ejemplo n.º 4
0
        public static RunResult Program(string fileName, string arguments, string workingDirectory)
        {
            var result = new RunResult();

            using (Process process = new Process())
            {
                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.FileName = fileName;
                process.StartInfo.Arguments = arguments;
                process.StartInfo.WorkingDirectory = workingDirectory;

                using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
                using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                {
                    process.OutputDataReceived += (sender, eventArgs) =>
                    {
                        if (eventArgs.Data == null)
                            outputWaitHandle.Set();
                        else
                            result.Output.Add(eventArgs.Data);
                    };

                    process.ErrorDataReceived += (sender, eventArgs) =>
                    {
                        if (eventArgs.Data == null)
                            outputWaitHandle.Set();
                        else
                            result.Errors.Add(eventArgs.Data);
                    };

                    process.Start();
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();

                    process.WaitForExit();

                    result.ExitCode = process.ExitCode;
                }
            }

            return result;
        }
Ejemplo n.º 5
0
        protected static RunResult http(string[] args)
        {
            //Invoke with 'args' and 'kwargs'
            var result = new RunResult();

            try
            {
                result = Core.Run(args);
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
                result.ExitCode = Consts.EXIT.ERROR;
            }

            return result;
        }
        /// <summary>
        ///     Runs a piece of code through the runner.
        /// </summary>
        /// <param name="runJob"></param>
        /// <returns></returns>
        public HttpResponseMessage Run(RunJob runJob)
        {
            var result = _compiler.CompileFromPlainText(_participant, runJob.Code);
            var runResult = _runner.Run(_participant);

            var response = new RunResult{
                BuildResult = new BuildController.BuildResult{
                    Output = result.StandardOutput,
                    Error = result.StandardError,
                    CompileTime = result.CompilationTime
                },
                Error = runResult.Error,
                Output = result.StandardError.Length > 0 ? "Build gefaald. Zie de build tab" : runResult.Output,
                RunTime = runResult.RunTime
            };

            return Request.CreateResponse(HttpStatusCode.Created, response);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 连续运行模式,支持打开某程序后,持续向其输入命令,直到结束。
        /// </summary>
        /// <param name="exePath"></param>
        /// <param name="args"></param>
        /// <param name="moreArgs"></param>
        /// <returns></returns>
        public static RunResult RunAsContinueMode(string exePath, string args, string[] moreArgs)
        {
            var result = new RunResult();

            try
            {
                using (var p = GetProcess())
                {
                    p.StartInfo.FileName  = exePath;
                    p.StartInfo.Arguments = args;
                    p.Start();

                    //先输出一个换行,以便将程序的第一行输出显示出来。
                    //如adb.exe,假如不调用此函数的话,第一行等待的shell@android:/ $必须等待下一个命令输入才会显示。
                    p.StandardInput.WriteLine();

                    result.OutputString = ReadStandardOutputLine(p);

                    result.MoreOutputString = new Dictionary <int, string>();
                    for (int i = 0; i < moreArgs.Length; i++)
                    {
                        p.StandardInput.WriteLine(moreArgs[i] + '\r');

                        //必须等待一定时间,让程序运行一会儿,马上读取会读出空的值。
                        Thread.Sleep(WaitTime);

                        result.MoreOutputString.Add(i, ReadStandardOutputLine(p));
                    }

                    p.WaitForExit();
                    result.ExitCode = p.ExitCode;
                    result.Success  = true;
                }
            }
            catch (Exception ex)
            {
                result.Success      = false;
                result.OutputString = ex.ToString();
            }
            return(result);
        }
Ejemplo n.º 8
0
        private RunResult RunEngine(InputModel inputModel)
        {
            RunResult result = null;

            try
            {
                var wordSequence = engine.Run(inputModel, WordLength);

                logger.LogInformation("Successfully generated result file");

                result = RunResult.Success(wordSequence);
            }
            catch (Exception ex)
            {
                result = RunResult.Failure(ex.Message);

                logger.LogError($"Unexpected error. Message: {ex.Message}");
            }

            return(result);
        }
Ejemplo n.º 9
0
        private static ScanResult ConvertRunResultToScanResult(RunResult runResult)
        {
            if (runResult == null)
            {
                throw new ArgumentNullException(nameof(runResult));
            }
            if (runResult.RuleInfo == null)
            {
                throw new ArgumentException(ErrorMessages.RunResultRuleInfoNull, nameof(runResult));
            }

            var scanResult = CreateResult(runResult.RuleInfo, runResult.element);

            var description = runResult.RuleInfo.Description;
            var ruleResult  = scanResult.GetRuleResultInstance(runResult.RuleInfo.ID, description);

            ruleResult.Status = ConvertEvaluationCodeToScanStatus(runResult.EvaluationCode);
            ruleResult.AddMessage(runResult.RuleInfo.HowToFix);

            return(scanResult);
        }
Ejemplo n.º 10
0
        public void showing_help_for_a_command(CraneRunner craneRunner, RunResult result, CraneTestContext craneTestContext)
        {
            "Given I have my own private copy of the crane console"
            ._(() => craneTestContext = ServiceLocator.Resolve <CraneTestContext>());

            "And I have a run context"
            ._(() => craneRunner = new CraneRunner());

            "When I run crane help init"
            ._(() => result = craneRunner.Command(craneTestContext.BuildOutputDirectory, "crane help init"));

            "Then crane outputs the usage statement for the command'"
            ._(() => result.StandardOutput.Line(0).Should().Contain("usage: crane init"));

            "And it should output the example usage"
            ._(() => result.StandardOutput.Should().Contain("example 1"));

            "And it should output the more information message"
            ._(() => result.StandardOutput.Should().Contain("For more information, visit"))
            .Teardown(() => craneTestContext.TearDown());
        }
Ejemplo n.º 11
0
        private static void flash(RunResult result)
        {
            switch (result)
            {
            case RunResult.Missing: Resources.mainWindow.label_emptyLight.Visible = true;
                Resources.mainWindow.label_passLight.Visible   = false;
                Resources.mainWindow.label_rejectLight.Visible = false;
                break;

            case RunResult.OK: Resources.mainWindow.label_emptyLight.Visible = false;
                Resources.mainWindow.label_passLight.Visible   = true;
                Resources.mainWindow.label_rejectLight.Visible = false;
                break;

            default:
                Resources.mainWindow.label_emptyLight.Visible  = false;
                Resources.mainWindow.label_passLight.Visible   = false;
                Resources.mainWindow.label_rejectLight.Visible = true;
                break;
            }
        }
Ejemplo n.º 12
0
        private static int RunSign(ISignArguments arguments, RunResult runResult)
        {
            Console.Out.WriteLine();
            Console.Out.WriteLine($"{nameof(RunSign)}");

            arguments.Validate();

            var inputData = runResult.HashedData.HasAny()
                ? runResult.HashedData
                : ByteArrayHelper.TranslateByteArray(arguments.InputData);

            Console.Out.WriteLine($"Using: {ByteArrayHelper.DescribeByteArray(inputData)}");

            var signingProvider = SigningProviderFactory.GetSigningProvider(arguments);

            runResult.SignedData = signingProvider.SignHash(inputData);

            Console.Out.WriteLine($"{nameof(RunResult.SignedData)}: {ByteArrayHelper.DescribeByteArray(runResult.SignedData)}");

            return(0);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Keep only the top K results from the history.
        /// </summary>
        /// <param name="history">set of all history.</param>
        /// <returns>The best K points contained in the history.</returns>
        private IRunResult[] TruncateHistory(IRunResult[] history)
        {
            SortedSet <RunResult> bestK = new SortedSet <RunResult>();

            foreach (RunResult r in history)
            {
                RunResult worst = bestK.Min();

                if (bestK.Count < _args.HistoryLength || r.CompareTo(worst) > 0)
                {
                    bestK.Add(r);
                }

                if (bestK.Count > _args.HistoryLength)
                {
                    bestK.Remove(worst);
                }
            }

            return(bestK.ToArray());
        }
Ejemplo n.º 14
0
        public RunResult Run()
        {
            var er = 0;
            var r  = new RunResult(this);

            while (true)
            {
                try
                {
                    var guid = Guid.NewGuid();
                    Console.WriteLine($"{DateTime.Now} Started {Db} {RecordCount} {guid} {er}");
                    Db.TableName = $"CRUDBenchmark_{guid.ToString().Replace("-", "_")}";

                    Db.Connect();
                    CreateTable();
                    r.Create = Create().TotalMilliseconds;
                    r.Read   = Read().TotalMilliseconds;
                    r.Update = Update().TotalMilliseconds;
                    r.Delete = Delete().TotalMilliseconds;
                    DropTable();
                    Db.Disconnect();

                    break;
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e);
                    Console.Error.WriteLine(e.StackTrace);
                    if (er++ > 5)
                    {
                        break;
                        //throw;
                    }
                }
            }

            Console.WriteLine($"{DateTime.Now} {JsonSerializer.Serialize(r)}");

            return(r);
        }
Ejemplo n.º 15
0
        public static void Main(String[] args)
        {
            String dirName = ".";

            if (args.Length > 0)
            {
                dirName = args[0];
            }
            DirectoryInfo dir = new DirectoryInfo(dirName);

            foreach (FileInfo file in dir.GetFiles())
            {
                try {
                    RunResult rr = RunResult.none;
                    if (file.Name.StartsWith("strict_"))
                    {
                        rr = RunResult.strict;
                    }
                    else if (file.Name.StartsWith("valid_"))
                    {
                        rr = RunResult.valid;
                    }
                    else if (file.Name.StartsWith("unverifiable_"))
                    {
                        rr = RunResult.unverifiable;
                    }
                    else if (file.Name.StartsWith("invalid_"))
                    {
                        rr = RunResult.invalid;
                    }

                    if (file.Name.EndsWith(".exe") && rr != RunResult.none)
                    {
                        executeTest(file.FullName, file.Name, rr);
                    }
                } catch (Exception e) {
                    Console.WriteLine("Warning: test {0} thrown exception {1}", file.FullName, e);
                }
            }
        }
Ejemplo n.º 16
0
        private static int RunHash(IHashArguments arguments, RunResult runResult)
        {
            Console.Out.WriteLine();
            Console.Out.WriteLine($"{nameof(RunHash)}");

            arguments.Validate();

            var inputData = arguments.InputData;

            Console.Out.WriteLine($"Using: {inputData}");

            runResult.UTF8EncodedData = Encoding.UTF8.GetBytes(inputData);
            Console.Out.WriteLine($"{nameof(RunResult.UTF8EncodedData)}: {ByteArrayHelper.DescribeByteArray(runResult.UTF8EncodedData)}");

            using (var hashProvider = new SHA256Managed())
            {
                runResult.HashedData = hashProvider.ComputeHash(runResult.UTF8EncodedData);
                Console.Out.WriteLine($"{nameof(RunResult.HashedData)} (SHA256): {ByteArrayHelper.DescribeByteArray(runResult.HashedData)}");
            }

            return(0);
        }
Ejemplo n.º 17
0
        private void runResults_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            // Look for RunResult for current participant and update this
            var rr = _raceRun.GetResultList().FirstOrDefault(r => r.Participant == this.Participant);

            if (rr != _rrMaster)
            {
                if (_rrMaster != null)
                {
                    _rrMaster.PropertyChanged -= rr_PropertyChanged;
                }

                _rrMaster = rr;

                if (_rrMaster != null)
                {
                    _rrMaster.PropertyChanged += rr_PropertyChanged;
                }

                UpdateRunResult(rr);
            }
        }
Ejemplo n.º 18
0
        public void PopulateWindow(RunResult runResult)
        {
            this.Title += " [" + runResult.TaskTitle + "]";

            lblExamplesPassed.Text = runResult.CorrectExamples + " / " + runResult.exampleResults.Count;

            foreach (ExampleResult exampleResult in runResult.exampleResults)
            {
                foreach (PropertyInfo propertyInfo in typeof(ExampleResult).GetProperties())
                {
                    TextBox label = new TextBox()
                    {
                        Text     = propertyInfo.Name + ": " + propertyInfo.GetValue(exampleResult, null),
                        FontSize = 14
                    };

                    StackPanel.Children.Add(label);
                }

                StackPanel.Children.Add(new Separator());
            }
        }
Ejemplo n.º 19
0
        public CheckResult Check(string inputFile, string outputFile, string answerFile)
        {
            string checkerArguments = string.Format(
                "{0} {1} {2} {3}",
                inputFile.Quote(),
                outputFile.Quote(),
                answerFile.Quote(),
                resultFile.Quote());
            RunResult runInfo = Run.WithDefaultLimits(checkerFile, checkerArguments, Path.GetDirectoryName(checkerFile));

            if (runInfo.Status != RunStatus.Ok)
            {
                throw new FailedActionException(
                          string.Format("получить результаты проверки от чекера {0}", checkerFile),
                          string.Format("Запуск чекера завершился со статусом {0}, код возврата {1}", runInfo.Status, runInfo.ExitCode));
            }
            return(new CheckResult
            {
                CheckerComment = File.ReadAllText(resultFile),
                CheckStatus = MapExitCodeToCheckStatus(runInfo.ExitCode),
            });
        }
Ejemplo n.º 20
0
        static RunResult runCommandCapturing(string command, string args, string workingDir = null)
        {
            RunResult rr = new RunResult();

            try
            {
                using (Process p = new Process())
                {
                    // set start info
                    p.StartInfo = new ProcessStartInfo(command, args)
                    {
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        UseShellExecute        = false,
                        WorkingDirectory       = string.IsNullOrWhiteSpace(workingDir) ? Path.GetTempPath() : workingDir,
                        CreateNoWindow         = true,
                        WindowStyle            = ProcessWindowStyle.Hidden
                    };
                    // note: outputData.appendLine should not be used because it can cause a break in the middle of a output line when the buffer is reached
                    p.OutputDataReceived += (sender, arg) => { rr.outputData.Append(arg.Data); rr.dataLineCnt++; };
                    p.ErrorDataReceived  += (sender, arg) => { rr.errorData.AppendLine(arg.Data); };
                    p.EnableRaisingEvents = false;
                    //p.Exited += onProcessExit;
                    p.Start();
                    p.BeginOutputReadLine();
                    p.BeginErrorReadLine();
                    p.WaitForExit(10000);   // wait 10s max

                    rr.exitCode = p.ExitCode;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message, ex);
                rr.errorData.AppendLine(ex.Message);
            }
            return(rr);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Does a mix of greedy local search around best performing parameter sets, while throwing random parameter sets into the mix.
        /// </summary>
        /// <param name="parents">Beginning locations for local greedy search.</param>
        /// <param name="forest">Trained random forest, used later for evaluating parameters.</param>
        /// <param name="numOfCandidates">Number of candidate configurations returned by the method (top K).</param>
        /// <param name="previousRuns">Historical run results.</param>
        /// <returns>Array of parameter sets, which will then be evaluated.</returns>
        private ParameterSet[] GreedyPlusRandomSearch(ParameterSet[] parents, FastForestRegressionPredictor forest, int numOfCandidates, IEnumerable <IRunResult> previousRuns)
        {
            // REVIEW: The IsMetricMaximizing flag affects the comparator, so that
            // performing Max() should get the best, regardless of if it is maximizing or
            // minimizing.
            RunResult bestRun  = (RunResult)previousRuns.Max();
            RunResult worstRun = (RunResult)previousRuns.Min();
            double    bestVal  = bestRun.IsMetricMaximizing ? bestRun.MetricValue : worstRun.MetricValue - bestRun.MetricValue;

            HashSet <Tuple <double, ParameterSet> > configurations = new HashSet <Tuple <double, ParameterSet> >();

            // Perform local search.
            foreach (ParameterSet c in parents)
            {
                Tuple <double, ParameterSet> bestChildKvp = LocalSearch(c, forest, bestVal, _args.Epsilon);
                configurations.Add(bestChildKvp);
            }

            // Additional set of random configurations to choose from during local search.
            ParameterSet[] randomConfigs = _randomSweeper.ProposeSweeps(_args.NumRandomEISearchConfigurations, previousRuns);
            double[]       randomEIs     = EvaluateConfigurationsByEI(forest, bestVal, randomConfigs);
            _host.Assert(randomConfigs.Length == randomEIs.Length);

            for (int i = 0; i < randomConfigs.Length; i++)
            {
                configurations.Add(new Tuple <double, ParameterSet>(randomEIs[i], randomConfigs[i]));
            }

            HashSet <ParameterSet> retainedConfigs = new HashSet <ParameterSet>();
            IOrderedEnumerable <Tuple <double, ParameterSet> > bestConfigurations = configurations.OrderByDescending(x => x.Item1);

            foreach (Tuple <double, ParameterSet> t in bestConfigurations.Take(numOfCandidates))
            {
                retainedConfigs.Add(t.Item2);
            }

            return(retainedConfigs.ToArray());
        }
        public async Task SoftStop()
        {
            ForEach <int> _forEach = Builder
                                     .For(Enumerable.Range(1, 100))
                                     .Each((T, token) =>
            {
                if (T == 50)
                {
                    throw new Exception();
                }

                return(Task.Delay(100, token));
            })
                                     .WithInitialDegreeOfParallelism(10)
                                     .WhenException((T, ex) => ExceptionResolution.SoftStop)
                                     .Build();

            RunResult result = await _forEach.Run(CancellationToken.None);

            Assert.AreEqual(RunResult.Interrupted, result);
            Assert.IsTrue(_forEach.RunStats.Started <= 60);
            Assert.IsTrue(_forEach.RunStats.Completed >= 40);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Executes an action.
        /// </summary>
        /// <param name="action"></param>
        /// <param name="exceptionMessageFetcher"></param>
        public static RunResult Execute(Action action, Func <string> exceptionMessageFetcher = null)
        {
            DateTime  start       = DateTime.Now;
            bool      success     = true;
            string    message     = string.Empty;
            Exception scriptError = null;

            try
            {
                action();
            }
            catch (Exception ex)
            {
                success = false;
                if (ex is LangException)
                {
                    LangException lex       = ex as LangException;
                    const string  langerror = "{0} : {1} at line : {2}, position: {3}";
                    message = string.Format(langerror, lex.Error.ErrorType, lex.Message, lex.Error.Line, lex.Error.Column);
                }
                else
                {
                    message = ex.Message;
                }

                scriptError = ex;
                if (exceptionMessageFetcher != null)
                {
                    message += exceptionMessageFetcher();
                }
            }
            DateTime end       = DateTime.Now;
            var      runResult = new RunResult(start, end, success, message);

            runResult.Ex = scriptError;
            return(runResult);
        }
Ejemplo n.º 24
0
        public bool Compile()
        {
            string reportFile = Path.Combine(workDir, NeTesterConfiguration.ReportFile);
            string script     = Path.Combine(workDir, NeTesterConfiguration.CompileScript);


            using (StreamWriter sw = new StreamWriter(script))
            {
                throw new NotImplementedException();
                //sw.Write(lang.CompileScript);
            }

            RunResult rr = new RunResult();

            using (DfyzProc prc = new DfyzProc(NeTesterConfiguration.ShellCommand, workDir, null))
            {
                prc.AddArgument(NeTesterConfiguration.ShellScriptParam);
                prc.AddArgument(script + " " + source + " " + exe);

                prc.SetCommonParams();

                prc.StdinRedirection        = DfyzProc.NULL_DEVICE;
                prc.StdoutRedirection       = reportFile;
                prc.DuplicateStdoutToStderr = true;

                rr = prc.Run();
            }
            if (rr.Status != RunStatus.Ok)
            {
                throw new NeTesterException("Compilation failed");
            }

            using (StreamReader sr = new StreamReader(reportFile))
                compReport = sr.ReadToEnd();

            return(rr.ExitCode == 0);
        }
Ejemplo n.º 25
0
        public static RunResult RunWaiting(string fileName, string arguments = null, string workingDirectory = "")
        {
            var res = new RunResult();
            var p   = new System.Diagnostics.Process
            {
                StartInfo = new System.Diagnostics.ProcessStartInfo
                {
                    WorkingDirectory       = workingDirectory,
                    FileName               = System.IO.Path.Combine(workingDirectory, fileName),
                    Arguments              = arguments,
                    UseShellExecute        = false,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                    CreateNoWindow         = true,
                }
            };

            p.OutputDataReceived += (s, a) => { if (a.Data == null)
                                                {
                                                    return;
                                                }
                                                res.Output.Add(a.Data); };
            p.ErrorDataReceived += (s, a) => { if (a.Data == null)
                                               {
                                                   return;
                                               }
                                               res.Error.Add(a.Data); };
            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            p.WaitForExit();
            p.CancelOutputRead();
            p.CancelErrorRead();
            res.Success = p.ExitCode == 0;
            return(res);
        }
Ejemplo n.º 26
0
        private void Execute(Action action, Func <string> exceptionMessageFetcher = null)
        {
            var       start       = DateTime.Now;
            var       success     = true;
            var       message     = string.Empty;
            Exception scriptError = null;

            try
            {
                action();
            }
            catch (Exception ex)
            {
                success = false;
                if (ex is LangException)
                {
                    var          lex       = ex as LangException;
                    const string langerror = "{0} : {1} at line : {2}, position: {3}";
                    message = string.Format(langerror, lex.Error.ErrorType, lex.Message, lex.Error.Line, lex.Error.Column);
                }
                else
                {
                    message = ex.Message;
                }

                scriptError = ex;
                if (exceptionMessageFetcher != null)
                {
                    message += exceptionMessageFetcher();
                }
            }
            var end = DateTime.Now;

            _runResult    = new RunResult(start, end, success, message);
            _runResult.Ex = scriptError;
        }
        public async Task HardStop()
        {
            bool hardStop = false;

            ForEach <int> _forEach = Builder
                                     .For(Enumerable.Range(1, 100))
                                     .Each(async(T, token) =>
            {
                if (T == 50)
                {
                    throw new Exception();
                }

                try
                {
                    await Task.Delay(100, token);
                }
                catch (OperationCanceledException)
                {
                    Assert.IsTrue(hardStop);
                }
            })
                                     .WithInitialDegreeOfParallelism(10)
                                     .WhenException((T, ex) =>
            {
                hardStop = true;
                return(ExceptionResolution.HardStop);
            })
                                     .Build();

            RunResult result = await _forEach.Run(CancellationToken.None);

            Assert.AreEqual(RunResult.Interrupted, result);
            Assert.IsTrue(_forEach.RunStats.Started <= 60);
            Assert.IsTrue(_forEach.RunStats.Completed >= 40);
        }
Ejemplo n.º 28
0
        private static string Format(RunResult result)
        {
            if (result.Passed)
            {
                return("");
            }
            string ret = (result.SpecificationName ?? result.FoundOnMemberInfo.Name) + " ";

            ret += (result.Passed ? "PASSED" : "FAILED") + " " + result.Message + "\n\n";
            if (result.Thrown != null)
            {
                ret += result.Thrown + "\n\n";
            }
            foreach (ExpectationResult exp in result.Expectations)
            {
                ret += "\t" + exp.Text + " " + (exp.Passed ? "PASSED" : "FAILED") + "\n";
                if (!exp.Passed)
                {
                    ret += exp.Exception.Message + "\n\n";
                }
            }
            ret += "\n---------------------------------------------------------------------------\n";
            return(ret);
        }
 public void Submit()
 {
     if (GeneralManager.CanSubmit)
     {
         playerName.interactable = false;
         btn.interactable        = false;
         RunResult result = GeneralManager.GetSubmiss();
         if (result.birdingScore > 0)
         {
             gateway.PostResult(
                 "birding",
                 playerName.text,
                 result.birdingScore.ToString(),
                 e => SetOwnPosition("birding", e[0].rank),
                 e => Debug.LogError(e)
                 );
         }
         if (result.birdingSpeed > 0)
         {
             gateway.PostResult(
                 "birdingxrunning",
                 playerName.text,
                 result.birdingSpeed.ToString("0.00"),
                 e => SetOwnPosition("birdingxrunning", e[0].rank),
                 e => Debug.LogError(e)
                 );
         }
         gateway.PostResult(
             "running",
             playerName.text,
             result.time.ToString("0.00"),
             e => SetOwnPosition("running", e[0].rank),
             e => Debug.LogError(e)
             );
     }
 }
Ejemplo n.º 30
0
        private void TxtStartNumber_TextChanged(object sender, TextChangedEventArgs e)
        {
            uint startNumber = 0U;

            try { startNumber = uint.Parse(txtStartNumber.Text); } catch (Exception) { }
            RaceParticipant participant = _thisRace.GetParticipant(startNumber);

            if (participant != null)
            {
                txtParticipant.Text = participant.Fullname;
                RunResult rr = _currentRaceRun.GetResultList().FirstOrDefault(r => r.Participant == participant);
                if (rr != null)
                {
                    txtStart.Text  = rr.GetStartTime()?.ToString(@"hh\:mm\:ss\,ffff");
                    txtFinish.Text = rr.GetFinishTime()?.ToString(@"hh\:mm\:ss\,ffff");
                    txtRun.Text    = rr.GetRunTime()?.ToString(@"mm\:ss\,ff");
                }
                else
                {
                    txtStart.Text  = "";
                    txtFinish.Text = "";
                    txtRun.Text    = "";
                }
            }
            else
            {
                txtParticipant.Text = "";
                txtStart.Text       = "";
                txtFinish.Text      = "";
                txtRun.Text         = "";
            }

            CheckTime(txtStart);
            CheckTime(txtFinish);
            CheckTime(txtRun);
        }
Ejemplo n.º 31
0
 public static void Listen_for_IOSignals_async()
 {
     Resources.ThreadListen = new Thread(() =>
     {
         var initialState = 1;
         while (true)
         {
             // Read signal of action from the IO card
             var triggered = read_IOC0640_step(ref initialState);
             if (!triggered)
             {
                 continue;
             }
             // Run the vision tool, refresh the image shown and get the run result
             RunResult runResult = runToolBlock_and_refreshImage();
             // Light effect for result visualization
             updateLights(runResult);
             // Submit the result back to the IO card
             // TODO: make this write async
             write_IOC0640_step(runResult);
         }
     });
     Resources.ThreadListen.Start();
 }
Ejemplo n.º 32
0
        static void DisplayGroupResults(IGrouping <int, RunResult> group)
        {
            Console.WriteLine("Benchmark {0}, Runner {1}, {2} iterations", group.First().BenchmarkType.Name,
                              group.First().RunnerType.Name, group.Key);

            Console.WriteLine();
            Console.WriteLine("{0,-30}{1,-14}{2,-12}{3,-10}{4,-12}{5,-12}{6}", "Implementation", "Duration",
                              "Difference", "Each",
                              "Multiplier", "Memory(KB)", "Throughput");
            Console.WriteLine(new string('=', 102));

            IOrderedEnumerable <RunResult> ordered = group.OrderBy(x => x.Duration);

            RunResult best = ordered.First();

            IEnumerable <DisplayResult> results = ordered.Select(x => new DisplayResult(x, best));

            foreach (DisplayResult x in results)
            {
                DisplayResult(group.Key, x);
            }

            Console.WriteLine();
        }
        private void OnSomethingChanged(object sender, RaceParticipant participantEnteredTrack, RaceParticipant participantLeftTrack, RunResult currentRunResult)
        {
            RaceParticipant particpant = null;

            string eventType = null;

            if (participantEnteredTrack != null)
            {
                eventType  = "Started";
                particpant = participantEnteredTrack;
            }
            if (participantLeftTrack != null)
            {
                eventType  = "Finished";
                particpant = participantLeftTrack;
            }

            string output = JsonConversion.ConvertEvent(particpant, eventType, currentRunResult);

            OnNewDataToSend(this, new NewDataEventArgs {
                Data = output
            });
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Builds up a phase result from start, end, success/message fields.
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="success"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public PhaseResult ToPhaseResult(DateTime start, DateTime end, bool success, string message)
        {
            var runResult = new RunResult(start, end, success, message);

            return(new PhaseResult(runResult));
        }
Ejemplo n.º 35
0
		static void executeTest (String path, String assemblyName, RunResult expected) {
			RunResult ad = testWithAppDomain (path, assemblyName);
			RunResult rt = testWithRuntime (path);
			RunResult pv = testWithPeverify (path);
			
			RunResult veredict = decide (ad, rt, pv, assemblyName);
			if (veredict != expected)
				Console.WriteLine ("ERROR: test {0} expected {1} but got {2} AD {3} RT {4} PV {5}", assemblyName, expected, veredict, ad, rt, pv);
		}
Ejemplo n.º 36
0
		static RunResult decide (RunResult ad, RunResult rt, RunResult pv, String testName) {
			if (ad == RunResult.valid) {
				if (rt != RunResult.valid) { 
					Console.WriteLine ("Warning: test {0} returned valid under AD but {1} under runtime. PV said {2}, using runtime choice", testName, rt, pv);
					return rt;
				}
				if (pv != RunResult.valid)
					return RunResult.strict;
				return RunResult.valid;
			}
			
			if (ad == RunResult.unverifiable) {
				//the rt test cannot complain about unverifiable

				if (pv == RunResult.valid)
					Console.WriteLine ("Warning: test {0} returned unverifiable under AD but {1} under PV, using AD choice", testName, pv);

				if (rt == RunResult.invalid) {
					/*This warning doesn't help a lot since there are cases which this happens
					Console.WriteLine ("Warning: test {0} returned unverifiable under AD but {1} under runtime. PV said {2}, using runtime choice", testName, rt, pv);
					*/
					
					return rt;
				}

				return RunResult.unverifiable;
			}

			if (ad == RunResult.invalid) {
				//in some cases the runtime throws exceptions meant for invalid code but the code is only unverifiable
				//we double check that by checking if rt returns ok
				
				if (pv == RunResult.valid)
					Console.WriteLine ("Warning: test {0} returned invalid under AD but {1} under PV, using AD choice", testName, pv);

				if (rt == RunResult.valid)
					return RunResult.unverifiable;

				return RunResult.invalid;
			}
			Console.WriteLine ("ERROR: test {0} returned an unknown result under ad {1}, runtime said {2} and PV {3} -- FIXME --", testName, ad, rt, pv);
			return RunResult.none;
		}
Ejemplo n.º 37
0
        public void OnAfterTestListCompleted(RunResult result)
        {
            string suiteName = result.Name.ToString();
            string failedCount = result.FailedCount.ToString();
            string passedCount = result.PassedCount.ToString();
            string notRunCount = result.NotRunCount.ToString();
            string totalCount = result.AllCount.ToString();
            string executionTime = (result.EndTime - result.StartTime).Hours.ToString() + " hrs " + (result.EndTime - result.StartTime).Minutes.ToString() + " min " + (result.EndTime - result.StartTime).Seconds.ToString() + " sec";
            string filePath = "C:\\Files\\ResultsXMLFile.xml";
            XmlTextWriter textWriter = new XmlTextWriter(filePath, null);
            textWriter.WriteStartDocument();
            textWriter.WriteComment("Xml file with test suite report");
            textWriter.WriteStartElement("Suite");
            textWriter.WriteAttributeString("title", "UI Test Automation Report");
            textWriter.WriteAttributeString("suitename", suiteName);
            textWriter.WriteAttributeString("total", totalCount);
            textWriter.WriteAttributeString("passed", passedCount);
            textWriter.WriteAttributeString("failed", failedCount);
            textWriter.WriteAttributeString("skipped", notRunCount);
            textWriter.WriteAttributeString("time", executionTime);
            textWriter.WriteAttributeString("browser", browserType);
            List<TestResult> list = result.TestResults;
            foreach (TestResult test in list)
            {
                string description = test.TestDescription;
                string testName = test.TestName;
                string startTime = test.StartTime.ToString();
                string endTime = test.EndTime.ToString();
                string duration = test.Duration.Minutes.ToString() + " min " + test.Duration.Seconds.ToString() + " sec";
                string testResult = test.Result.ToString().ToUpper();
                string testLog = test.Message.ToString();
                textWriter.WriteStartElement("Test");
                textWriter.WriteElementString("Name", testName);
                textWriter.WriteElementString("StartTime", startTime);
                textWriter.WriteElementString("EndTime", endTime);
                textWriter.WriteElementString("Duration", duration);
                textWriter.WriteElementString("Result", testResult);
                textWriter.WriteElementString("LogMessages", testLog);
                textWriter.WriteElementString("TestDescription", description);
                textWriter.WriteEndElement();
            }

            textWriter.WriteEndElement();
            textWriter.WriteEndDocument();
            textWriter.Close();

            string newXmlfile = @"C:\Files\XmlFile.xml";
            string oldXmlFile = filePath;
            CopyXmlDocument(oldXmlFile, newXmlfile);

            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load("C:\\Files\\CSEmailableReport.xslt");
            string htmlFilePath = "C:\\Files\\CSharpTestResultsreport" + (new Random().Next(1000000 - 1) + 1).ToString() + ".html";
            xslt.Transform(newXmlfile, htmlFilePath);

            StreamReader reader = new StreamReader(@"C:\Files\emailProperties.txt");
            Dictionary<string, string> emailProperties = new Dictionary<string, string>();
            while (reader.Peek() >= 0)
            {
                string line = reader.ReadLine();
                emailProperties.Add(line.Split('=')[0], line.Split('=')[1]);
            }
            MailAddress from = new MailAddress(emailProperties["fromAddress"]);

            MailMessage mail = new MailMessage()
            {
                From = from,
                Subject = "Test Results || Pacific || " + suiteName + " || Execution Time : " + executionTime + " || " + result.PassedPercent.ToString() + "% Passed || (" + passedCount + "/" + result.AllCount + ") Passed || Machine : " + result.Machine.NetworkName,
                Body = File.OpenText(htmlFilePath).ReadToEnd()
            };
            string[] toAddresses = emailProperties["toAddresses"].Split(',');
            foreach (string email in toAddresses)
            {
                mail.To.Add(new MailAddress(email));
            }
            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "pubsmtp.bedford.progress.com";
            smtp.Port = 25;
            smtp.Credentials = new NetworkCredential("*****@*****.**", "Pr@v@ll!k@23");
            smtp.Send(mail);
        }
Ejemplo n.º 38
0
        public void WhenIRunTheseCycles()
        {
            var controlSystem = new ControlSystem(_conveyor, _robot, new VaccumPort());

               results = controlSystem.DoStuff(_maxRunCycles,_cleanUpBound);
        }
Ejemplo n.º 39
0
        public async Task TestNelderMeadSweeperAsync()
        {
            var       random    = new Random(42);
            var       env       = new MLContext(42);
            const int batchSize = 5;
            const int sweeps    = 40;
            var       paramSets = new List <ParameterSet>();
            var       args      = new DeterministicSweeperAsync.Arguments();

            args.BatchSize  = batchSize;
            args.Relaxation = 0;

            args.Sweeper = ComponentFactoryUtils.CreateFromFunction(
                environ =>
            {
                var param = new IComponentFactory <INumericValueGenerator>[] {
                    ComponentFactoryUtils.CreateFromFunction(
                        innerEnviron => new FloatValueGenerator(new FloatParamArguments()
                    {
                        Name = "foo", Min = 1, Max = 5
                    })),
                    ComponentFactoryUtils.CreateFromFunction(
                        innerEnviron => new LongValueGenerator(new LongParamArguments()
                    {
                        Name = "bar", Min = 1, Max = 1000, LogBase = true
                    }))
                };

                var nelderMeadSweeperArgs = new NelderMeadSweeper.Arguments()
                {
                    SweptParameters   = param,
                    FirstBatchSweeper = ComponentFactoryUtils.CreateFromFunction <IValueGenerator[], ISweeper>(
                        (firstBatchSweeperEnviron, firstBatchSweeperArgs) =>
                        new RandomGridSweeper(environ, new RandomGridSweeper.Arguments()
                    {
                        SweptParameters = param
                    }))
                };

                return(new NelderMeadSweeper(environ, nelderMeadSweeperArgs));
            }
                );

            var sweeper = new DeterministicSweeperAsync(env, args);
            var mlock   = new object();

            double[] metrics = new double[sweeps];
            for (int i = 0; i < metrics.Length; i++)
            {
                metrics[i] = random.NextDouble();
            }

            for (int i = 0; i < sweeps; i++)
            {
                var paramWithId = await sweeper.Propose();

                if (paramWithId == null)
                {
                    return;
                }
                var result = new RunResult(paramWithId.ParameterSet, metrics[i], true);
                sweeper.Update(paramWithId.Id, result);
                lock (mlock)
                    paramSets.Add(paramWithId.ParameterSet);
            }
            Assert.True(paramSets.Count <= sweeps);
            CheckAsyncSweeperResult(paramSets);
        }
Ejemplo n.º 40
0
        public void TestDeterministicSweeperAsyncParallel()
        {
            var       random    = new Random(42);
            var       env       = new MLContext(42);
            const int batchSize = 5;
            const int sweeps    = 20;
            var       paramSets = new List <ParameterSet>();
            var       args      = new DeterministicSweeperAsync.Arguments();

            args.BatchSize  = batchSize;
            args.Relaxation = batchSize - 2;

            args.Sweeper = ComponentFactoryUtils.CreateFromFunction(
                environ => new SmacSweeper(environ,
                                           new SmacSweeper.Arguments()
            {
                SweptParameters = new IComponentFactory <INumericValueGenerator>[] {
                    ComponentFactoryUtils.CreateFromFunction(
                        t => new FloatValueGenerator(new FloatParamArguments()
                    {
                        Name = "foo", Min = 1, Max = 5
                    })),
                    ComponentFactoryUtils.CreateFromFunction(
                        t => new LongValueGenerator(new LongParamArguments()
                    {
                        Name = "bar", Min = 1, Max = 1000, LogBase = true
                    }))
                }
            }));

            var sweeper = new DeterministicSweeperAsync(env, args);

            var mlock   = new object();
            var options = new ParallelOptions();

            options.MaxDegreeOfParallelism = 4;

            // Sleep randomly to simulate doing work.
            int[] sleeps = new int[sweeps];
            for (int i = 0; i < sleeps.Length; i++)
            {
                sleeps[i] = random.Next(10, 100);
            }
            var r = Parallel.For(0, sweeps, options, (int i) =>
            {
                var task = sweeper.Propose();
                task.Wait();
                Assert.Equal(TaskStatus.RanToCompletion, task.Status);
                var paramWithId = task.Result;
                if (paramWithId == null)
                {
                    return;
                }
                Thread.Sleep(sleeps[i]);
                var result = new RunResult(paramWithId.ParameterSet, 0.42, true);
                sweeper.Update(paramWithId.Id, result);
                lock (mlock)
                    paramSets.Add(paramWithId.ParameterSet);
            });

            Assert.True(paramSets.Count <= sweeps);
            CheckAsyncSweeperResult(paramSets);
        }
Ejemplo n.º 41
0
 public abstract void GlobalExit(IWorldViewDictionary worldViewDictionary, RunResult result);
Ejemplo n.º 42
0
        public override void GlobalExit(IWorldViewDictionary worldViewDictionary, RunResult result)
        {
            var world = worldViewDictionary.GetWorldViewOfType<SeleniumWorldView>();

            world.Browser.Stop();
        }
Ejemplo n.º 43
0
 public CorrelatedResult(RunResult source, RunResult target)
 {
     Source = source;
     Target = target;
 }