Ejemplo n.º 1
0
        public void GetAssemblyPath_WithHashInDirectoryName()
        {
            string directoryPath        = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "#HashTestPath");
            string originalAssemblyPath = typeof(ReflectionUtilityTest).Assembly.Location;
            string newAssemblyPath      = Path.Combine(directoryPath, Path.GetFileName(originalAssemblyPath));

            if (Directory.Exists(directoryPath))
            {
                Directory.Delete(directoryPath, true);
            }

            Directory.CreateDirectory(directoryPath);
            try
            {
                File.Copy(originalAssemblyPath, newAssemblyPath);
                AppDomainRunner.Run(
                    delegate(object[] args)
                {
                    string directory    = (string)args[0];
                    string assemblyPath = (string)args[1];

                    Assembly assembly = Assembly.LoadFile(assemblyPath);
                    Assert.That(Path.GetDirectoryName(assembly.Location), Is.EqualTo(directory));
                    Assert.That(ReflectionUtility.GetAssemblyDirectory(assembly), Is.EqualTo(directory));
                },
                    directoryPath,
                    newAssemblyPath);
            }
            finally
            {
                Directory.Delete(directoryPath, true);
            }
        }
        public void ApplicationAssemblyInclusion_DependsOnAttribute()
        {
            string compiledAssemblyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NonApplicationMarkedAssembly.dll");

            try
            {
                AppDomainRunner.Run(
                    delegate(object[] args)
                {
                    var path = (string)args[0];

                    ApplicationAssemblyLoaderFilter filter = ApplicationAssemblyLoaderFilter.Instance;
                    Assert.That(filter.ShouldIncludeAssembly(typeof(AttributeAssemblyLoaderFilterTest).Assembly), Is.True);
                    Assert.That(filter.ShouldIncludeAssembly(typeof(TestFixtureAttribute).Assembly), Is.True);
                    Assert.That(filter.ShouldIncludeAssembly(typeof(ApplicationAssemblyLoaderFilter).Assembly), Is.True);
                    Assert.That(filter.ShouldIncludeAssembly(typeof(object).Assembly), Is.True);
                    Assert.That(filter.ShouldIncludeAssembly(typeof(Uri).Assembly), Is.True);

                    var assemblyCompiler = new AssemblyCompiler(@"Reflection\TypeDiscovery\TestAssemblies\NonApplicationMarkedAssembly", path,
                                                                typeof(NonApplicationAssemblyAttribute).Assembly.Location);
                    assemblyCompiler.Compile();
                    Assert.That(filter.ShouldIncludeAssembly(assemblyCompiler.CompiledAssembly), Is.False);
                }, compiledAssemblyPath);
            }
            finally
            {
                if (File.Exists(compiledAssemblyPath))
                {
                    FileUtility.DeleteAndWaitForCompletion(compiledAssemblyPath);
                }
            }
        }
Ejemplo n.º 3
0
        public void Execute()
        {
            var assembly = request.Container.Location;

            var testsToRun = context.GetTestsToRun().ToArray();

            var contexts = testsToRun
                           .Select(x => x.Context.TypeName)
                           .Distinct();

            var cache   = new ElementCache(testsToRun);
            var tracker = new RunTracker(testsToRun);

            var listener        = new TestExecutionListener(context, cache, token);
            var adapter         = new ExecutionAdapterRunListener(listener, cache, tracker);
            var loggingListener = new LoggingRunListener(adapter);
            var machineAdapter  = new AdapterListener(loggingListener, assembly);

            var runOptions = RunOptions.Custom.FilterBy(contexts);

            var runner = new AppDomainRunner(machineAdapter, runOptions);

            runner.RunAssembly(new AssemblyPath(request.Container.Location));

            listener.Finished.WaitOne();
        }
Ejemplo n.º 4
0
        private static void RunInAppDomain(IFrameworkHandle frameworkHandle, IGrouping <string, TestCase> source, List <TestCase> tests)
        {
            var dir = Path.GetDirectoryName(source.Key);
            var cmd = new RunTests
            {
                AssemblyName = Path.GetFileName(source.Key), AssemblyPath = dir, Source = source.Key,
            };
            var dto = new List <TestCaseToRun>();

            foreach (TestCase testCase in tests)
            {
                var parts = testCase.FullyQualifiedName.Split('.');
                dto.Add(new TestCaseToRun(testCase.FullyQualifiedName)
                {
                    TestClassName  = parts[parts.Length - 2],
                    TestMethodName = parts[parts.Length - 1]
                });
            }

            using (var appDomainRunner = new AppDomainRunner(source.Key))
            {
                appDomainRunner.AddDirectory(dir);
                appDomainRunner.Create();


                var resultProxy = new TestResultProxy(frameworkHandle, tests);
                appDomainRunner.RunTests(cmd, resultProxy);
            }
        }
        public void DoesntChangeCurrentSetup()
        {
            string dynamicBaseBefore = AppDomain.CurrentDomain.SetupInformation.DynamicBase;

            AppDomainRunner.Run(delegate { new AppDomainRunnerTest(); });
            Assert.That(AppDomain.CurrentDomain.SetupInformation.DynamicBase, Is.EqualTo(dynamicBaseBefore));
        }
 public void SpecificAppBase()
 {
     AppDomainRunner.Run(@"C:\", delegate(object[] args)
     {
         Assert.That(AppDomain.CurrentDomain.BaseDirectory, Is.EqualTo(@"C:\"));
     });
 }
        /// <summary>
        /// Executes the task.
        /// </summary>
        protected override void ExecuteTask()
        {
            DisplayTaskConfiguration();

            if (FileSetHelper.Count(Assemblies) == 0)
            {
                Log(Level.Warning, "No specification assemblies, aborting task");
                return;
            }

            List <ISpecificationRunListener> listeners = SetUpListeners();
            NAntRunListener nantRunListener            = new NAntRunListener(this);

            listeners.Add(nantRunListener);

            AggregateRunListener rootListener = new AggregateRunListener(listeners);
            ISpecificationRunner runner       = new AppDomainRunner(rootListener, RunOptions.Default);

            RunSpecifications(Assemblies, runner);

            Log(Level.Info, "Finished running specs");

            if (nantRunListener.FailureOccurred)
            {
                throw new BuildException("There were failing specifications. Please see the build log.");
            }
        }
Ejemplo n.º 8
0
        public void Run(TestContext context)
        {
            var environment = new TestEnvironment(context.AssemblyTask);
            var listener    = new TestRunListener(_taskServer, context);

            var runOptions = RunOptions.Custom.FilterBy(context.GetContextNames());

            if (environment.ShouldShadowCopy)
            {
                runOptions.ShadowCopyTo(environment.ShadowCopyPath);
                _taskServer.SetTempFolderPath(environment.ShadowCopyPath);
            }

            var appDomainRunner = new AppDomainRunner(listener, runOptions);

            try
            {
                appDomainRunner.RunAssembly(new AssemblyPath(environment.AssemblyPath));
            }
            catch (Exception e)
            {
                _taskServer.ShowNotification("Unable to run tests: " + e.Message, string.Empty);
                _taskServer.TaskException(context.AssemblyTask, new[] { new TaskException(e) });
            }
        }
 public void GetDefaultQueryFilePath_ThrowsIfNoQueryFileExists()
 {
     AppDomainRunner.Run(@"C:\", delegate
     {
         QueryConfiguration configuration = new QueryConfiguration();
         configuration.GetDefaultQueryFilePath();
     });
 }
        public TestRunState RunMember(ITestListener testListener, Assembly assembly, MemberInfo member)
        {
            var listener = new TDNetRunListener(testListener);
            var runner   = new AppDomainRunner(listener, RunOptions.Default);

            runner.RunMember(assembly, member);

            return(listener.TestRunState);
        }
        public TestRunState RunNamespace(ITestListener testListener, Assembly assembly, string ns)
        {
            var listener = new TDNetRunListener(testListener);
            var runner   = new AppDomainRunner(listener, RunOptions.Default);

            runner.RunNamespace(assembly, ns);

            return(listener.TestRunState);
        }
Ejemplo n.º 12
0
        public TestRunState RunAssembly(ITestListener testListener, Assembly assembly)
        {
            var listener = new TDNetRunListener(testListener);
            var runner   = new AppDomainRunner(listener, RunOptions.Default);

            runner.RunAssembly(new AssemblyPath(assembly.Location));

            return(listener.TestRunState);
        }
Ejemplo n.º 13
0
 public IEnumerable<TestResult> Run(RunSettings settings)
 {
     _results = new List<TestResult>();
         var listener = new TestListener(_feedback, settings.Assembly.Assembly);
         var assembly = getAssembly(settings.Assembly.Assembly);
         var runner = new AppDomainRunner(listener, Machine.Specifications.Runner.RunOptions.Default);
         runTests(settings, assembly, runner);
         _results.AddRange(listener.Results);
         return _results;
 }
        public void AppDomainIsCreated()
        {
            AppDomain current = AppDomain.CurrentDomain;

            AppDomainRunner.Run(
                delegate(object[] args)
            {
                Assert.That(AppDomain.CurrentDomain.FriendlyName, Is.EqualTo("AppDomainRunner - AppDomain"));
                Assert.That(AppDomain.CurrentDomain, Is.Not.SameAs(args[0]));
            },
                current);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Evaluates the chromosome's fitness.
        /// </summary>
        public override async Task EvaluateAsync(IChromosome chromosome)
        {
            try
            {
                // cast to the base type
                var chromosomeBase = (Chromosome)chromosome;

                // Convert to dictionary and add "id" key-value pair
                var list = chromosomeBase.ToDictionary();
                list.Add("chromosome-id", chromosomeBase.Id);

                // Set algorithm start and end dates
                list.Add("start-date", StartDate.ToString("O"));
                list.Add("end-date", EndDate.ToString("O"));

                // Additional settings to the list
                list.Add("algorithm-type-name", Shared.Config.AlgorithmTypeName);
                list.Add("algorithm-location", Shared.Config.AlgorithmLocation);
                list.Add("data-folder", Shared.Config.DataFolder);

                // Obtain full results
                var result = await Task.Run(() => AppDomainRunner.RunAlgorithm(list));

                // Calculate fitness and concat the results with an output string
                var fitness = StatisticsAdapter.CalculateFitness(result, FitnessScore, FilterEnabled);

                // Save full results
                chromosomeBase.FitnessResult = new FitnessResult
                {
                    Chromosome  = chromosomeBase,
                    StartDate   = this.StartDate,
                    EndDate     = this.EndDate,
                    FullResults = result
                };

                // create an output string
                var theOutput = chromosomeBase.EvaluationToLogOutput(result, FitnessScore, fitness);

                // Display the output
                lock (_lock)
                {
                    Shared.Logger.Trace(theOutput + Environment.NewLine);
                }

                // assign a value to chromosome fitness
                chromosome.Fitness = fitness;
            }
            catch (Exception ex)
            {
                Shared.Logger.Error("OptimizerFitness.Evaluate: " + ex.Message);
            }
        }
        public void ArgumentsArePassedInCorrectly()
        {
            AppDomainRunner.Run(delegate(object[] args)
            {
                Assert.That(args.Length, Is.EqualTo(2));
                Assert.That("Foo", Is.EqualTo(args[0]));
                Assert.That(4, Is.EqualTo(args[1]));
            }, "Foo", 4);

            AppDomainRunner.Run(delegate(object[] args)
            {
                Assert.That(args.Length, Is.EqualTo(0));
            });
        }
Ejemplo n.º 17
0
 private void runTests(RunSettings settings, Assembly assembly, AppDomainRunner runner)
 {
     if (runAllTests(settings))
         {
             runner.RunAssembly(assembly);
             return;
         }
         foreach (var member in settings.Assembly.Tests)
             runner.RunMember(assembly, assembly.GetType(member));
         foreach (var member in settings.Assembly.Members)
             runner.RunMember(assembly, assembly.GetType(member));
         foreach (var ns in settings.Assembly.Namespaces)
             runner.RunNamespace(assembly, ns);
 }
Ejemplo n.º 18
0
        public TestRunState RunAssembly(ITestListener testListener, Assembly assembly)
        {
            var listener = new TDNetRunListener(testListener);
            var runner   = new AppDomainRunner(listener, RunOptions.Default);

            try
            {
                runner.StartRun(assembly);
                runner.RunAssembly(assembly);
            }
            finally
            {
                runner.EndRun(assembly);
            }

            return(listener.TestRunState);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Inits computation resources
        /// </summary>
        public static void Initialize()
        {
            // Computation mode specific settings: azure or app domain ?
            switch (Shared.Config.TaskExecutionMode)
            {
            case TaskExecutionMode.Azure:
                AzureBatchManager.InitializeAsync().Wait();
                break;

            case TaskExecutionMode.Linear:
            case TaskExecutionMode.Parallel:
                AppDomainRunner.Initialize();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 20
0
        private static ExitCode RunAssembly(Assembly assembly, RunOptions runOptions)
        {
            ISpecificationRunListener listener = new BufferedAssemblyTeamCityReporter(WriteToTeamCity);

            ISpecificationRunner specificationRunner = new AppDomainRunner(listener, runOptions);

            specificationRunner.RunAssembly(assembly);

            if (listener is ISpecificationResultProvider)
            {
                var errorProvider = (ISpecificationResultProvider)listener;
                if (errorProvider.FailureOccurred)
                {
                    return(ExitCode.Failure);
                }
            }

            return(ExitCode.Success);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Releases the computation resources at the end of optimization routine
        /// </summary>
        public static void Dispose()
        {
            // -1- Clean up Task Execution resources
            switch (Shared.Config.TaskExecutionMode)
            {
            case TaskExecutionMode.Azure:
                AzureBatchManager.DisposeAsync().Wait();
                break;

            case TaskExecutionMode.Linear:
            case TaskExecutionMode.Parallel:
                // -2- Release AppDomain
                AppDomainRunner.Dispose();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public void FindAssemblies_FindsReferencedAssemblies_Transitive()
        {
            const string buildOutputDirectory = "Reflection.AssemblyFinderTest.FindAssemblies_FindsReferencedAssemblies_Transitive";
            const string sourceDirectoryRoot  = @"Reflection\TypeDiscovery\AssemblyFinding\TestAssemblies\AssemblyFinderTest";

            Action <object[]> testAction = delegate(object[] args)
            {
                var outputManagerWithoutClosure = (AssemblyCompilerBuildOutputManager)args[0];

                // dependency chain: mixinSamples -> remotion -> log4net
                var log4NetAssembly     = typeof(log4net.LogManager).Assembly;
                var remotionAssembly    = typeof(AssemblyFinder).Assembly;
                var referencingAssembly = CompileReferencingAssembly(outputManagerWithoutClosure, remotionAssembly);

                var loaderMock = MockRepository.GenerateMock <IAssemblyLoader>();
                loaderMock
                .Expect(mock => mock.TryLoadAssembly(ArgReferenceMatchesDefinition(remotionAssembly), Arg.Is(referencingAssembly.FullName)))
                // load re-motion via samples
                .Return(remotionAssembly);
                loaderMock
                .Expect(mock => mock.TryLoadAssembly(ArgReferenceMatchesDefinition(log4NetAssembly), Arg.Is(remotionAssembly.FullName)))
                // load log4net via re-motion
                .Return(log4NetAssembly);
                loaderMock.Replay();

                var rootAssemblyFinderStub = MockRepository.GenerateMock <IRootAssemblyFinder>();
                rootAssemblyFinderStub.Stub(stub => stub.FindRootAssemblies()).Return(
                    new[] { new RootAssembly(referencingAssembly, true) });
                rootAssemblyFinderStub.Replay();

                var finder = new AssemblyFinder(rootAssemblyFinderStub, loaderMock);
                var result = finder.FindAssemblies();

                loaderMock.VerifyAllExpectations();
                Assert.That(result, Is.EquivalentTo(new[] { referencingAssembly, remotionAssembly, log4NetAssembly }));
            };

            // Run test action in separate AppDomain
            using (var outputManager = new AssemblyCompilerBuildOutputManager(buildOutputDirectory, true, sourceDirectoryRoot))
            {
                AppDomainRunner.Run(testAction, outputManager);
            }
        }
        public override void ExecuteRecursive(TaskExecutionNode node)
        {
            var task = (RunAssemblyTask)node.RemoteTask;

            var contextAssembly = LoadContextAssembly(task);

            if (contextAssembly == null)
            {
                return;
            }

            var result = VersionCompatibilityChecker.Check(contextAssembly);

            if (!result.Success)
            {
                Server.TaskException(node.RemoteTask, new[] { new TaskException("no type", result.ErrorMessage, null) });

                return;
            }

            var listener = new PerAssemblyRunListener(Server, task);
            var runner   = new AppDomainRunner(listener, RunOptions.Default);
            var runScope = GetRunScope(runner);

            node.Flatten(x => x.Children).Each(children => RegisterRemoteTaskNotifications(listener, children));

            try
            {
                runScope.StartRun(contextAssembly);

                foreach (var child in node.Children)
                {
                    RunContext(runner, contextAssembly, child);
                }
            }
            finally
            {
                runScope.EndRun(contextAssembly);
            }
        }
        public void SavesMixedTypes()
        {
            AppDomainRunner.Run(
                delegate
            {
                using (MixinConfiguration.BuildNew()
                       .ForClass <BaseType1>().AddMixins(typeof(BT1Mixin1))
                       .ForClass <Page> ().AddMixin(typeof(NullMixin))
                       .EnterScope())
                {
                    Mixer mixer = Mixer.Create("Assembly", _assemblyOutputDirectory, 1);
                    mixer.PrepareOutputDirectory();
                    mixer.Execute(MixinConfiguration.ActiveConfiguration);

                    Assembly theAssembly = Assembly.LoadFile(mixer.MixerPipelineFactory.GetModulePaths(_assemblyOutputDirectory).Single());
                    var types            = theAssembly.GetTypes();

                    var concreteType = types.SingleOrDefault(t => t.BaseType == typeof(BaseType1));
                    Assert.NotNull(concreteType);
                    Assert.That(
                        MixinTypeUtility.GetClassContextForConcreteType(concreteType),
                        Is.EqualTo(MixinConfiguration.ActiveConfiguration.GetContext(typeof(BaseType1))));

                    object instance = Activator.CreateInstance(concreteType);
                    Assert.That(Mixin.Get <BT1Mixin1> (instance), Is.Not.Null);

                    var concreteTypeFromSystemAssembly = types.SingleOrDefault(t => t.BaseType == typeof(Page));
                    Assert.That(concreteTypeFromSystemAssembly, Is.Not.Null);

                    SafeServiceLocator.Current.GetInstance <IPipelineRegistry>().DefaultPipeline.CodeManager.LoadFlushedCode(theAssembly);

                    Type concreteTypeFromFactory = TypeFactory.GetConcreteType(typeof(BaseType1));
                    Assert.That(concreteTypeFromFactory, Is.SameAs(concreteType));

                    Assert.That(theAssembly.IsDefined(typeof(NonApplicationAssemblyAttribute), false), Is.True);
                }
            });
        }
        public override void ExecuteRecursive(TaskExecutionNode node)
        {
            var task = (RunAssemblyTask)node.RemoteTask;

            var priorCurrentDirectory = Environment.CurrentDirectory;

            try
            {
                // Use the assembly in the folder that the user has specified, or, if not, use the assembly location
                var assemblyFolder = GetAssemblyFolder(TaskExecutor.Configuration, task);
                var assemblyPath   = new AssemblyPath(Path.Combine(assemblyFolder, GetFileName(task.AssemblyLocation)));

                Environment.CurrentDirectory = assemblyFolder;

                var listener    = new PerAssemblyRunListener(Server, task);
                var contextList = new List <string>();
                node.Flatten(x => x.Children).Each(children => RegisterRemoteTaskNotifications(listener, children, contextList));

                var runOptions      = RunOptions.Custom.FilterBy(contextList);
                var appDomainRunner = new AppDomainRunner(listener, runOptions);

                if (TaskExecutor.Configuration.ShadowCopy)
                {
                    string cachePath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

                    runOptions.ShadowCopyTo(cachePath);
                    this.Server.SetTempFolderPath(cachePath);
                }

                appDomainRunner.RunAssembly(assemblyPath);
            }
            finally
            {
                Environment.CurrentDirectory = priorCurrentDirectory;
            }
        }
Ejemplo n.º 26
0
        static async Task Main(string[] args)
        {
            var discoverer = new TestDiscoverer();

            discoverer.Load(new[] { typeof(IncidentWrapper).Assembly });
            var runner = new TestRunner(discoverer);

            runner.Load(new[] { typeof(IncidentWrapper).Assembly }).GetAwaiter().GetResult();
            var result = runner.RunAll().GetAwaiter().GetResult();
            var faulty = result.Where(x => !x.IsSuccess).ToList();

            var cmd = new RunTests
            {
                AssemblyName = typeof(EnvironmentTests).Assembly.GetName().Name,
                AssemblyPath = Path.GetDirectoryName(typeof(EnvironmentTests).Assembly.Location),
                //TestCases = new[]
                //{
                //    new TestCaseToRun("Coderr.IntegrationTests.Core.TestCases.EnvironmentTests.Clearing_environment_should_remove_all_incidents_in_it")
                //    {
                //        TestClassName = "EnvironmentTests",
                //        TestMethodName = "Clearing_environment_should_remove_all_incidents_in_it"
                //    },
                //},
                Source = typeof(EnvironmentTests).Assembly.Location
            };

            var receiver = new ConsoleReceiver();

            using (var coordinator = new AppDomainRunner("TesTSuite1"))
            {
                coordinator.Create();
                coordinator.AddDirectory(
                    @"C:\src\1tcompany\coderr\oss\Coderr.Server\src\Tools\Coderr.IntegrationTests\Coderr.IntegrationTests\bin\Debug\net461");
                coordinator.RunTests(cmd, receiver);
            }
        }
Ejemplo n.º 27
0
        public ExitCode Run(string[] arguments)
        {
            ExceptionReporter reporter = new ExceptionReporter(_console);

            Options options = new Options();

            if (!options.ParseArguments(arguments))
            {
                _console.WriteLine(Options.Usage());
                return(ExitCode.Failure);
            }

            List <ISpecificationRunListener> listeners = new List <ISpecificationRunListener>();

            var timingListener = new TimingRunListener();

            listeners.Add(timingListener);
            listeners.Add(new AssemblyLocationAwareListener());

            ISpecificationRunListener mainListener;

            if (options.TeamCityIntegration ||
                (!options.DisableTeamCityAutodetection &&
                 Environment.GetEnvironmentVariable("TEAMCITY_PROJECT_NAME") != null))
            {
                mainListener = new TeamCityReporter(_console.WriteLine, timingListener);
            }
            else
            {
                mainListener = new RunListener(_console, options.Silent, timingListener);
            }

            try
            {
                if (!String.IsNullOrEmpty(options.HtmlPath))
                {
                    if (IsHtmlPathValid(options.HtmlPath))
                    {
                        listeners.Add(GetHtmlReportListener(options));
                    }
                    else
                    {
                        _console.WriteLine("Invalid html path:" + options.HtmlPath);
                        _console.WriteLine(Options.Usage());
                        return(ExitCode.Failure);
                    }
                }

                if (!String.IsNullOrEmpty(options.XmlPath))
                {
                    if (IsHtmlPathValid(options.XmlPath))
                    {
                        listeners.Add(GetXmlReportListener(options, timingListener));
                    }
                    else
                    {
                        _console.WriteLine("Invalid xml path:" + options.XmlPath);
                        _console.WriteLine(Options.Usage());
                        return(ExitCode.Failure);
                    }
                }

                listeners.Add(mainListener);

                if (options.AssemblyFiles.Count == 0)
                {
                    _console.WriteLine(Options.Usage());
                    return(ExitCode.Failure);
                }

                var listener = new AggregateRunListener(listeners);

                ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions());
                List <Assembly>      assemblies          = new List <Assembly>();
                foreach (string assemblyName in options.AssemblyFiles)
                {
                    if (!File.Exists(assemblyName))
                    {
                        throw NewException.MissingAssembly(assemblyName);
                    }

                    Assembly assembly = Assembly.LoadFrom(assemblyName);
                    assemblies.Add(assembly);
                }

                if (options.WaitForDebugger)
                {
                    WaitForDebugger();
                    if (Debugger.IsAttached == false)
                    {
                        _console.WriteLine("Fatal error: Timeout while waiting for debugger to attach");
                        return(ExitCode.Failure);
                    }
                }

                specificationRunner.RunAssemblies(assemblies);
            }
            catch (Exception ex)
            {
                reporter.ReportException(ex);
                return(ExitCode.Error);
            }

            if (mainListener is ISpecificationResultProvider)
            {
                var errorProvider = (ISpecificationResultProvider)mainListener;
                if (errorProvider.FailureOccurred)
                {
                    return(ExitCode.Failure);
                }
            }
            return(ExitCode.Success);
        }
Ejemplo n.º 28
0
        public ExitCode Run(string[] arguments)
        {
            ExceptionReporter reporter = new ExceptionReporter(_console);

            Options options = new Options();
            if (!options.ParseArguments(arguments))
            {
                _console.WriteLine(Resources.UsageStatement);
                return ExitCode.Failure;
            }

            List<ISpecificationRunListener> listeners = new List<ISpecificationRunListener>();

            var timingListener = new TimingRunListener();
            listeners.Add(timingListener);
            listeners.Add(new AssemblyLocationAwareListener());

            ISpecificationRunListener mainListener;
            if (options.TeamCityIntegration)
            {
                mainListener = new TeamCityReporter(_console.WriteLine, timingListener);
            }
            else
            {
                mainListener = new RunListener(_console, options.Silent, timingListener);
            }

            try
            {
                if (SetupCustomListeners(options, listeners, timingListener))
                {
                    return ExitCode.Failure;
                }

                listeners.Add(mainListener);

                if (options.AssemblyFiles.Count == 0)
                {
                    _console.WriteLine(Resources.UsageStatement);
                    return ExitCode.Failure;
                }

                var listener = new AggregateRunListener(listeners);

                ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions());
                List<Assembly> assemblies = new List<Assembly>();
                foreach (string assemblyName in options.AssemblyFiles)
                {
                    if (!File.Exists(assemblyName))
                    {
                        throw NewException.MissingAssembly(assemblyName);
                    }

                    Assembly assembly = Assembly.LoadFrom(assemblyName);
                    assemblies.Add(assembly);
                }

                specificationRunner.RunAssemblies(assemblies);
            }
            catch (Exception ex)
            {
                reporter.ReportException(ex);
                return ExitCode.Error;
            }

            if (mainListener is ISpecificationResultProvider)
            {
                var errorProvider = (ISpecificationResultProvider)mainListener;
                if (errorProvider.FailureOccurred)
                {
                    return ExitCode.Failure;
                }
            }

            return ExitCode.Success;
        }
Ejemplo n.º 29
0
        public ExitCode Run(string[] arguments)
        {
            ExceptionReporter reporter = new ExceptionReporter(_console);

            Options options = new Options();

            if (!options.ParseArguments(arguments))
            {
                _console.WriteLine(Options.Usage());
                return(ExitCode.Failure);
            }

            List <ISpecificationRunListener> listeners = new List <ISpecificationRunListener>();

            var timingListener = new TimingRunListener();

            listeners.Add(timingListener);
            listeners.Add(new AssemblyLocationAwareListener());

            ISpecificationRunListener mainListener;

            if (options.TeamCityIntegration)
            {
                mainListener = new TeamCityReporter(_console.WriteLine, timingListener);
            }
            else
            {
                mainListener = new RunListener(_console, options.Silent, timingListener);
            }

            try
            {
                if (!String.IsNullOrEmpty(options.HtmlPath))
                {
                    if (IsHtmlPathValid(options.HtmlPath))
                    {
                        listeners.Add(GetHtmlReportListener(options));
                    }
                    else
                    {
                        _console.WriteLine("Invalid html path:" + options.HtmlPath);
                        _console.WriteLine(Options.Usage());
                        return(ExitCode.Failure);
                    }
                }

                if (!String.IsNullOrEmpty(options.XmlPath))
                {
                    if (IsHtmlPathValid(options.XmlPath))
                    {
                        listeners.Add(GetXmlReportListener(options, timingListener));
                    }
                    else
                    {
                        _console.WriteLine("Invalid xml path:" + options.XmlPath);
                        _console.WriteLine(Options.Usage());
                        return(ExitCode.Failure);
                    }
                }

                listeners.Add(mainListener);

                if (options.AssemblyFiles.Count == 0)
                {
                    _console.WriteLine(Options.Usage());
                    return(ExitCode.Failure);
                }

                var listener = new AggregateRunListener(listeners);

                ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions());
                List <Assembly>      assemblies          = new List <Assembly>();
                foreach (string assemblyName in options.AssemblyFiles)
                {
                    if (!File.Exists(assemblyName))
                    {
                        throw NewException.MissingAssembly(assemblyName);
                    }

                    Assembly assembly = Assembly.LoadFrom(assemblyName);
                    assemblies.Add(assembly);
                }

                specificationRunner.RunAssemblies(assemblies);
            }
            catch (Exception ex)
            {
                reporter.ReportException(ex);
                return(ExitCode.Error);
            }

            if (mainListener is ISpecificationResultProvider)
            {
                var errorProvider = (ISpecificationResultProvider)mainListener;
                if (errorProvider.FailureOccurred)
                {
                    return(ExitCode.Failure);
                }
            }
            return(ExitCode.Success);
        }
Ejemplo n.º 30
0
 static void Main(string[] args)
 {
     AppDomainRunner.Marshalling();
 }
Ejemplo n.º 31
0
        public ExitCode Run(string[] arguments)
        {
            ExceptionReporter reporter = new ExceptionReporter(_console);

            Options options = new Options();

            if (!options.ParseArguments(arguments))
            {
                _console.WriteLine(Options.Usage());
                return(ExitCode.Failure);
            }

            var timer     = new TimingRunListener();
            var listeners = new List <ISpecificationRunListener>
            {
                timer
            };

            ISpecificationRunListener mainListener;

            if (options.TeamCityIntegration ||
                (!options.DisableTeamCityAutodetection &&
                 Environment.GetEnvironmentVariable("TEAMCITY_PROJECT_NAME") != null))
            {
                mainListener = new TeamCityReporter(_console.WriteLine, timer);
            }
            else
            {
                mainListener = new RunListener(_console, DetermineOutput(options, _console), timer);
            }

            try
            {
                if (!String.IsNullOrEmpty(options.HtmlPath))
                {
                    if (IsHtmlPathValid(options.HtmlPath))
                    {
                        listeners.Add(GetHtmlReportListener(options));
                    }
                    else
                    {
                        _console.WriteLine("Invalid html path: {0}", options.HtmlPath);
                        _console.WriteLine(Options.Usage());
                        return(ExitCode.Failure);
                    }
                }

                if (!String.IsNullOrEmpty(options.XmlPath))
                {
                    if (IsHtmlPathValid(options.XmlPath))
                    {
                        listeners.Add(GetXmlReportListener(options, timer));
                    }
                    else
                    {
                        _console.WriteLine("Invalid xml path: {0}", options.XmlPath);
                        _console.WriteLine(Options.Usage());
                        return(ExitCode.Failure);
                    }
                }

                listeners.Add(mainListener);

                if (options.AssemblyFiles.Count == 0)
                {
                    _console.WriteLine(Options.Usage());
                    return(ExitCode.Failure);
                }

                var listener = new AggregateRunListener(listeners);

                ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions());
                List <Assembly>      assemblies          = new List <Assembly>();
                foreach (string assemblyName in options.AssemblyFiles)
                {
                    if (!File.Exists(assemblyName))
                    {
                        throw NewException.MissingAssembly(assemblyName);
                    }

                    var excludedAssemblies = new[] { "Machine.Specifications.dll", "Machine.Specifications.Clr4.dll" };
                    if (excludedAssemblies.Any(x => Path.GetFileName(assemblyName) == x))
                    {
                        _console.WriteLine("Warning: Excluded {0} from the test run because the file name matches either of these: {1}", assemblyName, String.Join(", ", excludedAssemblies));
                        continue;
                    }

                    Assembly assembly = Assembly.LoadFrom(assemblyName);
                    assemblies.Add(assembly);
                }

                if (options.WaitForDebugger)
                {
                    WaitForDebugger();
                    if (Debugger.IsAttached == false)
                    {
                        _console.WriteLine("Fatal error: Timeout while waiting for debugger to attach");
                        return(ExitCode.Failure);
                    }
                }

                specificationRunner.RunAssemblies(assemblies);
            }
            catch (Exception ex)
            {
                reporter.ReportException(ex);
                return(ExitCode.Error);
            }

            if (mainListener is ISpecificationResultProvider)
            {
                var errorProvider = (ISpecificationResultProvider)mainListener;
                if (errorProvider.FailureOccurred)
                {
                    return(ExitCode.Failure);
                }
            }
            return(ExitCode.Success);
        }