Пример #1
0
        public int Main()
        {
            consoleOut.WriteLine("Start time: {0}", DateTime.Now.ToShortTimeString());
            // add path
            foreach (string assemblyPath in this.Arguments.AssemblyPath)
            {
                this.resolver.AddHintDirectory(assemblyPath);
            }

            // store real console
            listener.Writer = Console.Out;
            timer.Start();
            try
            {
                ReportResult   result = new ReportResult();
                IFixtureFilter filter = arguments.GetFilter();

                if (this.Arguments.Files.Length == 0)
                {
                    consoleOut.WriteLine("[warning] No test assemblies to execute");
                }
                else
                {
                    consoleOut.WriteLine("[info] Loading test assemblies");
                    using (
                        TestDomainDependencyGraph graph =
                            TestDomainDependencyGraph.BuildGraph(
                                this.Arguments.Files,
                                this.Arguments.AssemblyPath,
                                filter, this.Arguments.Verbose))
                    {
                        //define an assembly resolver routine in case the CLR cannot find our assemblies.
                        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolveHandler);


                        graph.Log += new ErrorReporter(graph_Log);
                        consoleOut.WriteLine("[info] Starting execution");
                        ReportResult r = graph.RunTests();
                        graph.Log -= new ErrorReporter(graph_Log);
                        result.Merge(r);
                    }
                }

                this.GenerateReport(arguments, result);
                timer.Stop();
                consoleOut.WriteLine("[info] MbUnit execution finished in {0}s.", timer.Duration);
                return((0 == result.Counter.FailureCount) ? 0 : -1);
            }
            catch (System.Runtime.Remoting.RemotingException remote)
            {
                consoleOut.WriteLine("Could not load test domain.  Please ensure you have referenced the installed version of MbUnit.Framework within your test assembly. \r\n The error message was: \r\n" + remote.Message);
                return(-3);
            }
            catch (Exception ex)
            {
                consoleOut.WriteLine(ex.ToString());
                return(-3);
            }
        }
Пример #2
0
        public void StartStopImmediately()
        {
            TimeMonitor timer = new TimeMonitor();

            timer.Start();
            timer.Stop();
            Assert.LowerEqualThan(0, timer.Duration);
        }
Пример #3
0
            public override void Run(object fixture)
            {
                TimeMonitor monitor = new TimeMonitor();

                monitor.Start();
                this.TestCase.Run(fixture);
                monitor.Stop();

                Assert.IsLowerEqual(monitor.Duration, this.Attribute.MaxDuration);
            }
Пример #4
0
        public void StartStopShowValues()
        {
            TimeMonitor timer = new TimeMonitor();

            timer.Start();
            Random rnd = new Random();

            for (int i = 0; i < 10000; ++i)
            {
                rnd.NextDouble();
            }
            timer.Stop();
            TypeHelper.ShowPropertyValues(timer);
        }
Пример #5
0
        public static void TestAnimal(int iterations)
        {
            var tm = new TimeMonitor();

            // Run iterations
            for (var i = 0; i < iterations; i++)
            {
                var cm = new OrganismEmulator();

                tm.Start();
                cm.EmulateOrganism();
                lastQuanta = tm.EndGetMicroseconds();

                allQuanta.Add(lastQuanta);
            }

            // Sort by speed
            allQuanta.Sort();

            // Pick the middle 80% of all iterations
            for (var i = (int)(iterations * 0.15); i < (int)(iterations * 0.85); i++)
            {
                samples++;
                lastQuanta = (long)allQuanta[i];

                if (worstQuanta == 0 && bestQuanta == 0)
                {
                    worstQuanta = lastQuanta;
                    bestQuanta  = lastQuanta;
                }
                else
                {
                    if (lastQuanta > worstQuanta)
                    {
                        worstQuanta = lastQuanta;
                    }

                    if (lastQuanta < bestQuanta)
                    {
                        bestQuanta = lastQuanta;
                    }
                }

                totalQuanta += lastQuanta;
            }
        }
Пример #6
0
        public override Object Execute(Object o, IList args)
        {
            timer.Start();
            // run test
            Object result = this.Invoker.Execute(o, args);

            timer.Stop();
            // checkl time is in bounds
            if (timer.Duration <= this.MinDuration || timer.Duration >= this.MaxDuration)
            {
                throw new MethodDurationException(
                          this.MinDuration,
                          this.MaxDuration,
                          timer.Duration,
                          this,
                          o,
                          args
                          );
            }

            return(result);
        }
Пример #7
0
 /// <summary>
 /// Start the progress from zero
 /// </summary>
 /// <param name="totalRecords">Number of records we are going to progress through</param>
 /// <param name="percentageOfBar">% of progress we are to fill on first stage</param>
 /// <param name="message">Message to display</param>
 public void Reset(int totalRecords = 0, double percentageOfBar = 100, string message = null)
 {
     ProgressBarValue = 0; //at start of the progress bar
     TimeMonitor.Start();
     NextStage(totalRecords, percentageOfBar, message);
 }
Пример #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CountDownTimer"/> and starts it.
 /// </summary>
 /// <param name="maxDuration">The maximum duration for the timer</param>
 public CountDownTimer(double maxDuration)
 {
     this.maxDuration = maxDuration;
     this.timer       = new TimeMonitor();
     timer.Start();
 }
Пример #9
0
        // This routine is run on the activationThread.  It just waits until a new animal is ready to
        // be run and then runs it and waits again.  There are two ways we attempt to mitigate the
        // fact that an animal may not want to return execution and hang the machine:
        //
        // 1. The threadTimer timer is started before we start executing animal code, and
        //      if the animal takes too long, the _threadTimer will fire and run a routine
        //      that calls ThreadAbort on this thread. There are ways for animals to hog the
        //      thread such that this won't ever get a chance to abort them.  See #2 for
        //      mitigation of this.
        // 2. The RunAnimalWithDeadlockDetection() is what actually feeds animals into the
        //      ActivateBug() routine.  RunAnimalWithDeadlockDetection() provides the next
        //      circle of protection by monitoring the thread with a much longer duration.
        //      if the thread never comes back (which means that ThreadAbort must be failing)
        //      then RunAnimalWithDeadlockDetection() will restart the game and permanently
        //      blacklist the animal.
        internal void ActivateBug()
        {
            // First retreive the thread handle for this thread so we can get accurate reads on how
            // much actual time an animal spent executing.
            // This is a pseudo handle that can't be used on other threads until it is duplicated
            var pseudoThreadHandle = GetCurrentThread();

            _threadHandleValid = DuplicateHandle(
                _processHandle,     // handle to source process
                pseudoThreadHandle, // handle to duplicate
                _processHandle,     // handle to target process
                ref _threadHandle,  // duplicate handle
                0,                  // requested access
                false,              // handle inheritance option
                2                   // optional actions
                );

            // Notify the constructor of this class that we have retreived the handle.
            var setSuccess = _handleRetrieved.Set();

            Debug.Assert(setSuccess);

            // If we get an exception that somehow happens outside the try blocks below, it will end this thread,
            // be caught by our global exception handler and our deadlock logic will restart the game automatically because
            // it will think the thread never came back and is deadlocked.
            while (true)
            {
                // Wait for the first animal
                _animalReady.WaitOne();
                if (_exitAnimalThread)
                {
                    return;
                }

                var   success       = false;
                Int64 duration      = 0;
                var   deathReason   = PopulationChangeReason.NotDead;
                var   exceptionInfo = "";
                var   skippedTurn   = false;

                // short circut inactive bugs
                if (_bug.Active)
                {
                    var state = CurrentState.GetOrganismState(_bug.Organism.ID);
                    if (!state.IsAlive)
                    {
                        _bug.Active = false;
                    }
                    else
                    {
                        try
                        {
                            try
                            {
                                // See if the animal has consistently taken too much time and has finally
                                // gone over the maxAllowance.
                                if (_bug.Overage > MaxAllowance)
                                {
                                    Trace.WriteLine("Organism blacklisted: bug.Overage > _maxAllowance");
                                    deathReason = PopulationChangeReason.Timeout;
                                    _bug.Active = false;
                                }
                                else if (_bug.Overage > MaxOverage)
                                {
                                    // if the bug is overtime, don't schedule it
                                    // but deduce one quantum from its overage
                                    // until it's back under the allowable limit
                                    _bug.Overage -= Quantum;
                                    if (_bug.Overage < 0)
                                    {
                                        _bug.Overage = 0;
                                    }

                                    // We still need to call InternalMain with "true" so that it can clear
                                    // out state for event handlers.  This won't run organism code
                                    _bug.Organism.InternalMain(true);

                                    _bug.Organism.WriteTrace(
                                        "Animal's turn was skipped because they took longer than " +
                                        Quantum + " microseconds for their turn too many times.");

                                    // We didn't fail, we're just skipping them.  Don't remove them from the world.
                                    success     = true;
                                    skippedTurn = true;
                                }
                                else
                                {
                                    // Start the thread that will ensure we ThreadAbort if the elapsed
                                    // time the animal takes is too long.
                                    startTimer();

                                    // Time the animal
                                    _monitor.Start();

                                    // Tell the timer thread it is OK to abort in this section
                                    // If a ThreadAbort exception gets thrown from after this lock statement on down to
                                    // safeToAbort = false, we won't shut off safeToAbort and we could abort again in the
                                    // catch handlers which is why we are wrapped with another try  / catch block
                                    lock (_monitor)
                                    {
                                        _safeToAbort = true;
                                    }

                                    // Hook up the tracing event handler if the animal is selected
                                    if (GameConfig.LoggingMode != "None")
                                    {
                                        if (GameConfig.LoggingMode != "Full")
                                        {
                                            var renderInfo = _bug.Organism.State.RenderInfo;
                                            if (renderInfo != null && ((TerrariumSprite)renderInfo).Selected)
                                            {
                                                _bug.Organism.Trace += traceEventHandler;
                                            }
                                        }
                                        else
                                        {
                                            _bug.Organism.Trace += traceEventHandler;
                                        }
                                    }

                                    // Actually allow the animal to run their code now.
                                    _bug.Organism.InternalMain(false);

                                    // Tell the timer thread it is not OK to abort anymore
                                    // If we get aborted before this can complete, the aborter will
                                    // set this to false as well
                                    lock (_monitor)
                                    {
                                        _safeToAbort = false;
                                    }

                                    cancelTimer();

                                    // Determine how much time the animal spent
                                    duration = _monitor.EndGetMicroseconds();

                                    // This means we weren't aborted or didn't throw an exception
                                    success = true;
                                }
                            }
                            catch (ThreadAbortException)
                            {
                                // If we get aborted, the aborter will set safeToAbort to false so no need
                                // to do it here
                                deathReason = PopulationChangeReason.Timeout;
                                Trace.WriteLine("Inner Try ThreadAborted");
                                Thread.ResetAbort();
                                Trace.WriteLine("Cancelling Timer");
                                cancelTimer();
                            }
                            catch (SecurityException e)
                            {
                                // Tell the timer thread it is not OK to abort anymore
                                // If we get aborted before this can complete, the aborter will set this
                                // to false as well
                                lock (_monitor)
                                {
                                    _safeToAbort = false;
                                }

                                cancelTimer();

                                // Organism needs to be removed from the game because it had an exception
                                deathReason   = PopulationChangeReason.SecurityViolation;
                                exceptionInfo = e.ToString();
                            }
                            catch (OrganismBlacklistedException)
                            {
                                // This exception gets thrown when we try to give a time slice to an animal
                                // that has been replaced by the special TerrariumOrganism, whose whole purpose
                                // is to just replace a blacklisted animal until it is safe to remove them
                                // from the game, which is now.

                                // Tell the timer thread it is not OK to abort anymore
                                // If we get aborted before this can complete, the aborter will set this
                                // to false as well
                                lock (_monitor)
                                {
                                    _safeToAbort = false;
                                }

                                cancelTimer();

                                deathReason = PopulationChangeReason.OrganismBlacklisted;
                            }
                            catch (Exception e)
                            {
                                // Tell the timer thread it is not OK to abort anymore
                                // If we get aborted before this can complete, the aborter will set this
                                // to false as well
                                lock (_monitor)
                                {
                                    _safeToAbort = false;
                                }

                                cancelTimer();

                                // Organism needs to be removed from the game because it had an exception
                                deathReason   = PopulationChangeReason.Error;
                                exceptionInfo = e.ToString();
                            }
                        }
                        catch (ThreadAbortException)
                        {
                            // if we catch the abort here in the outer of the two try blocks, there was an exception,
                            // but we lost it since the threadabort happened in the catch handler
                            if (deathReason == PopulationChangeReason.NotDead)
                            {
                                deathReason   = PopulationChangeReason.Error;
                                exceptionInfo = "Exception was lost because organism timed out before we could grab it.";
                            }
                            Thread.ResetAbort();
                            Trace.WriteLine("Outer Try ThreadAborted");
                        }
                        finally
                        {
                            _bug.Organism.Trace -= traceEventHandler;
                            if (!success)
                            {
                                // Organism needs to be removed from the game because it had an exception
                                if (deathReason == PopulationChangeReason.Timeout)
                                {
                                    _currentEngine.RemoveOrganismQueued(new KilledOrganism(_bug.Organism.ID, deathReason));
                                }
                                else
                                {
                                    // The organism threw an exception
                                    _currentEngine.RemoveOrganismQueued(new KilledOrganism(_bug.Organism.ID, deathReason,
                                                                                           exceptionInfo));
                                    Trace.WriteLine("Exception in Animal: \r\n" + exceptionInfo);
                                }
                            }
                            else
                            {
                                _totalActivations++;
                                if (PenalizeForTime)
                                {
                                    _bug.TotalTime += duration;
                                    _bug.LastTime   = duration;
                                    if (duration > Quantum)
                                    {
                                        _bug.Overage += (duration - Quantum);
                                    }
                                    else if (_bug.Overage > 0 && !skippedTurn)
                                    {
                                        // If the animal ran under time, subtract this off of
                                        // their overage
                                        _bug.Overage -= (Quantum - duration);
                                        if (_bug.Overage < 0)
                                        {
                                            _bug.Overage = 0;
                                        }
                                    }
                                }
                                else
                                {
                                    _bug.LastTime = duration;
                                    _bug.Overage  = 0;
                                }

                                _bug.TotalActivations++;
                            }
                        }

                        if (_totalActivations > _lastReport + ReportInterval)
                        {
                            _lastReport = _totalActivations;
                        }
                    }
                }

                // Tell the UI thread we are done with this animal
                _animalReady.Reset();
                _animalDone.Set();
            }
        }