Example #1
0
        static void InitializeTraceLevel()
        {
            string             traceLevel = ConfigManager.OptionSection.Options["Options.InternalTraceLevel"].Value;
            InternalTraceLevel level      = (InternalTraceLevel)Enum.Parse(InternalTraceLevel.Default.GetType(), traceLevel, true);

            InternalTrace.Initialize("CodeBuilder_%p.log", level);
        }
        private void Initialize(string assemblyPath, IDictionary settings)
        {
            AssemblyNameOrPath = assemblyPath;

            var newSettings = settings as IDictionary <string, object>;

            Settings = newSettings ?? settings.Cast <DictionaryEntry>().ToDictionary(de => (string)de.Key, de => de.Value);

            if (Settings.ContainsKey(PackageSettings.InternalTraceLevel))
            {
                var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)Settings[PackageSettings.InternalTraceLevel], true);

                if (Settings.ContainsKey(PackageSettings.InternalTraceWriter))
                {
                    InternalTrace.Initialize((TextWriter)Settings[PackageSettings.InternalTraceWriter], traceLevel);
                }
#if !PORTABLE && !SILVERLIGHT
                else
                {
                    var workDirectory = Settings.ContainsKey(PackageSettings.WorkDirectory) ? (string)Settings[PackageSettings.WorkDirectory] : Env.DefaultWorkDirectory;
                    var logName       = string.Format(LOG_FILE_FORMAT, Process.GetCurrentProcess().Id, Path.GetFileName(assemblyPath));
                    InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
                }
#endif
            }
        }
        private void Initialize(string assemblyPath, IDictionary settings)
        {
            AssemblyNameOrPath = assemblyPath;

            var newSettings = settings as IDictionary <string, object>;

            Settings = newSettings ?? settings.Cast <DictionaryEntry>().ToDictionary(de => (string)de.Key, de => de.Value);

            if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceLevel))
            {
                var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)Settings[FrameworkPackageSettings.InternalTraceLevel], true);

                if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceWriter))
                {
                    InternalTrace.Initialize((TextWriter)Settings[FrameworkPackageSettings.InternalTraceWriter], traceLevel);
                }
                else
                {
                    var workDirectory = Settings.ContainsKey(FrameworkPackageSettings.WorkDirectory)
                        ? (string)Settings[FrameworkPackageSettings.WorkDirectory]
                        : Directory.GetCurrentDirectory();
#if NETSTANDARD1_6
                    var id = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
#else
                    var id = Process.GetCurrentProcess().Id;
#endif
                    var logName = string.Format(LOG_FILE_FORMAT, id, Path.GetFileName(assemblyPath));
                    InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
                }
            }
        }
Example #4
0
        ///// <summary>
        ///// Access the public IServiceLocator, first initializing
        ///// the services if that has not already been done.
        ///// </summary>
        //IServiceLocator ITestEngine.Services
        //{
        //    get
        //    {
        //        if(!Services.ServiceManager.ServicesInitialized)
        //            Initialize();

        //        return Services;
        //    }
        //}

        /// <summary>
        /// Initialize the engine. This includes initializing mono addins,
        /// setting the trace level and creating the standard set of services
        /// used in the Engine.
        ///
        /// This interface is not normally called by user code. Programs linking
        /// only to the testcentric.engine.api assembly are given a
        /// pre-initialized instance of TestEngine. Programs
        /// that link directly to testcentric.engine usually do so
        /// in order to perform custom initialization.
        /// </summary>
        public void InitializeServices()
        {
            if (InternalTraceLevel != InternalTraceLevel.Off && !InternalTrace.Initialized)
            {
                var logName = string.Format("InternalTrace.{0}.log", Process.GetCurrentProcess().Id);
                InternalTrace.Initialize(Path.Combine(WorkDirectory, logName), InternalTraceLevel);
            }

            // If caller added services beforehand, we don't add any
            if (Services.ServiceCount == 0)
            {
                // Services that depend on other services must be added after their dependencies
                // For example, ResultService uses ExtensionService, so ExtensionService is added
                // later.
                Services.Add(new DriverService());
#if !NETSTANDARD1_6
                Services.Add(new ExtensionService());
#if !NETSTANDARD2_0
                Services.Add(new DomainManager());
#endif
#endif
                Services.Add(new InProcessTestRunnerFactory());
            }

            Services.ServiceManager.StartServices();
        }
Example #5
0
        /// <summary>
        /// Create and initialize the standard set of services
        /// used in the Engine. This interface is not normally
        /// called by user code. Programs linking only to
        /// only to the nunit.engine.api assembly are given a
        /// pre-initialized instance of TestEngine. Programs
        /// that link directly to nunit.engine usually do so
        /// in order to perform custom initialization.
        /// </summary>
        public void InitializeServices()
        {
            SettingsService settingsService = new SettingsService(true);

            if (InternalTraceLevel == InternalTraceLevel.Default)
            {
                InternalTraceLevel = (InternalTraceLevel)settingsService.GetSetting("Options.InternalTraceLevel", InternalTraceLevel.Off);
            }

            if (InternalTraceLevel != InternalTraceLevel.Off)
            {
                var logName = string.Format("InternalTrace.{0}.log", Process.GetCurrentProcess().Id);
                InternalTrace.Initialize(Path.Combine(WorkDirectory, logName), InternalTraceLevel);
            }

            this.Services.Add(settingsService);
            this.Services.Add(new RecentFilesService());
            this.Services.Add(new DomainManager());
            this.Services.Add(new ProjectService());
            this.Services.Add(new RuntimeFrameworkSelector());
            this.Services.Add(new DefaultTestRunnerFactory());
            this.Services.Add(new DriverFactory());
            this.Services.Add(new TestAgency());
            this.Services.Add(new ResultService());

            this.Services.ServiceManager.InitializeServices();
        }
Example #6
0
        /// <summary>
        /// Initialize the engine. This includes initializing mono addins,
        /// setting the trace level and creating the standard set of services
        /// used in the Engine.
        ///
        /// This interface is not normally called by user code. Programs linking
        /// only to the nunit.engine.api assembly are given a
        /// pre-initialized instance of TestEngine. Programs
        /// that link directly to nunit.engine usually do so
        /// in order to perform custom initialization.
        /// </summary>
        public void Initialize()
        {
            if (InternalTraceLevel != InternalTraceLevel.Off && !InternalTrace.Initialized)
            {
                var logName = string.Format("InternalTrace.{0}.log", Process.GetCurrentProcess().Id);
                InternalTrace.Initialize(Path.Combine(WorkDirectory, logName), InternalTraceLevel);
            }

            // If caller added services beforehand, we don't add any
            if (Services.ServiceCount == 0)
            {
                // Services that depend on other services must be added after their dependencies
                // For example, ResultService uses ExtensionService, so ExtensionService is added
                // later.
                Services.Add(new SettingsService(true));
                Services.Add(new RecentFilesService());
                Services.Add(new TestFilterService());
                Services.Add(new ExtensionService());
                Services.Add(new ProjectService());
#if NETFRAMEWORK
                Services.Add(new DomainManager());
                Services.Add(new RuntimeFrameworkService());
                Services.Add(new TestAgency());
#endif
                Services.Add(new DriverService());
                Services.Add(new ResultService());
                Services.Add(new DefaultTestRunnerFactory());
            }

            Services.ServiceManager.StartServices();
        }
Example #7
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            try
            {
                InitializeTraceLevel();

                AppContainer container = new AppContainer();
                MainForm     form      = new MainForm();
                container.Add(form);

                logger.Info(Resources.StartingCodeBuilder);
                Application.Run(form);
                logger.Info(Resources.CodeBuilderExit);
            }
            catch (Exception ex)
            {
                logger.Error(Resources.Startup, ex);
                MessageBoxHelper.DisplayFailure(ex.Message);
            }

            InternalTrace.Close();
        }
Example #8
0
        public static void Main(string[] args)
        {
            var options = new AgentOptions(args);
            var pid     = Process.GetCurrentProcess().Id;
            var logName = $"testcentric-agent_{pid}.log";

            InternalTrace.Initialize(Path.Combine(options.WorkDirectory, logName), options.TraceLevel);
            log = InternalTrace.GetLogger(typeof(TestCentricAgent));

            if (options.DebugAgent || options.DebugTests)
            {
                TryLaunchDebugger();
            }

            LocateAgencyProcess(options.AgencyPid);

            log.Info("Agent process {0} starting", pid);

#if NET5_0
            log.Info($"Running .NET 5.0 agent under {RuntimeInformation.FrameworkDescription}");
#elif NETCOREAPP3_1
            log.Info($"Running .NET Core 3.1 agent under {RuntimeInformation.FrameworkDescription}");
#elif NETCOREAPP2_1
            log.Info($"Running .NET Core 2.1 agent under {RuntimeInformation.FrameworkDescription}");
#elif NET40
            log.Info("Running .NET Framework 4.0 agent");
#elif NET20
            log.Info("Running .NET Framework 2.0 agent");
#endif

            log.Info("Starting RemoteTestAgent");
            Agent           = new RemoteTestAgent(options.AgentId);
            Agent.Transport =
#if NETFRAMEWORK
                new TestCentric.Engine.Communication.Transports.Remoting.TestAgentRemotingTransport(Agent, options.AgencyUrl);
#else
                new TestCentric.Engine.Communication.Transports.Tcp.TestAgentTcpTransport(Agent, options.AgencyUrl);
#endif
            try
            {
                if (Agent.Start())
                {
                    WaitForStop();
                }
                else
                {
                    log.Error("Failed to start RemoteTestAgent");
                    Environment.Exit(AgentExitCodes.FAILED_TO_START_REMOTE_AGENT);
                }
            }
            catch (Exception ex)
            {
                log.Error("Exception in RemoteTestAgent. {0}", ExceptionHelper.BuildMessageAndStackTrace(ex));
                Environment.Exit(AgentExitCodes.UNEXPECTED_EXCEPTION);
            }
            log.Info("Agent process {0} exiting cleanly", pid);

            Environment.Exit(AgentExitCodes.OK);
        }
Example #9
0
        public static int Main(string[] args)
        {
            InternalTrace.Initialize("nunit-console_%p.log");

            return(Runner.Main(args));

            //InternalTrace.Close();
        }
Example #10
0
 /// <summary>
 /// Initialize the engine. This includes initializing mono addins,
 /// setting the trace level and creating the standard set of services
 /// used in the Engine.
 ///
 /// This interface is not normally called by user code. Programs linking
 /// only to the nunit.engine.api assembly are given a
 /// pre-initialized instance of TestEngine. Programs
 /// that link directly to nunit.engine usually do so
 /// in order to perform custom initialization.
 /// </summary>
 public void Initialize()
 {
     if (InternalTraceLevel != InternalTraceLevel.Off && !InternalTrace.Initialized)
     {
         var logName = string.Format("InternalTrace.{0}.log", Process.GetCurrentProcess().Id);
         InternalTrace.Initialize(Path.Combine(WorkDirectory, logName), InternalTraceLevel);
     }
 }
Example #11
0
        static void Main()
        {
            // preinstance
            //
            if (Diagnostics.HasPreInstance())
            {
                NUnit.UiKit.UserMessage.Display(strings.AppRunning);
                return;
            }

            if (EnableExceptionHandle)
            {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(
                    Application_ThreadException);
            }

            InternalTrace.Initialize("CommuniServer_%p.log");

            CSDBI csdbi = CSDBI.Instance;

            YeHeCommuniServerApp.Default.CSDBI = csdbi;


            csdbi.VerifyDBInfo(Config.Default.ProjectName, Config.Default.MajorVersion,
                               Config.Default.MinorVersion, Config.Default.RevisionVersion);

            DeviceDefineBuilderBase d = new XmlDeviceDefinePathBuild("xml");

            System.Data.DataTable tblStation = YeHeCommuniServerApp.Default.CSDBI.ExecuteStationDataTable();
            System.Data.DataTable tblDevice  = YeHeCommuniServerApp.Default.CSDBI.ExecuteDeviceDataTable();
            HardwareBuilderBase   h          = new DBHardWareBuilder(tblStation, tblDevice);

            TaskFactoryCollectionBuilder t = new XmlTaskFactoryCollectionBuilder("xml\\task.xml");
            ListenBuilderBase            l = new XmlListenBuilder("xml\\listenport.xml");

            // create communisoft
            //
            Hashtable settings = new Hashtable();

            settings.Add("TaskTimeout", Config.Default.TaskTimeout);
            //CommuniSoftFactory.get.Create(settings);

            CommuniSoftFactory.Init(h);
            YeHeCommuniServerApp.Default.CommuniSoft = CommuniSoft.Default;


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMain());
            Config.Default.Save();

            object obj = XD221ModbusConfigObject.XD221ConfigDefineCollection;
        }
Example #12
0
        private void InitializeInternalTrace(string assemblyPath, InternalTraceLevel traceLevel)
        {
            if (traceLevel != InternalTraceLevel.Off)
            {
#if !SILVERLIGHT
                var logName = string.Format(LOG_FILE_FORMAT, Process.GetCurrentProcess().Id, Path.GetFileName(assemblyPath));
#else
                var logName = string.Format(LOG_FILE_FORMAT, DateTime.Now.ToString("o"), Path.GetFileName(assemblyPath));
#endif
                InternalTrace.Initialize(Path.Combine(Environment.CurrentDirectory, logName), traceLevel);
            }
        }
Example #13
0
        public NUnitWrapper()
        {
            InternalTrace.Initialize("nunit-visual-mutator.log", InternalTraceLevel.Verbose);

            CoreExtensions.Host.InitializeService();
            ServiceManager.Services.AddService(new SettingsService());
            ServiceManager.Services.AddService(new DomainManager());
            ServiceManager.Services.AddService(new RecentFilesService());
            ServiceManager.Services.AddService(new ProjectService());
            ServiceManager.Services.AddService(new AddinRegistry());
            ServiceManager.Services.AddService(new AddinManager());
            ServiceManager.Services.AddService(new TestAgency());
        }
Example #14
0
        public static ITestModel CreateTestModel(ITestEngine testEngine, CommandLineOptions options)
        {
            // Currently the InternalTraceLevel can only be set from the command-line.
            // We can't use user settings to provide a default because the settings
            // are an engine service and the engine have the internal trace level
            // set as part of its initialization.
            var traceLevel = options.InternalTraceLevel != null
                ? (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), options.InternalTraceLevel)
                : InternalTraceLevel.Off;

            // This initializes the trace setting for the process.
            InternalTrace.Initialize($"InternalTrace.{Process.GetCurrentProcess().Id}.gui.log", traceLevel);

            testEngine.InternalTraceLevel = traceLevel;
            if (options.WorkDirectory != null)
            {
                testEngine.WorkDirectory = options.WorkDirectory;
            }

            var model = new TestModel(testEngine, "TestCentric");


            model.PackageOverrides.Add(EnginePackageSettings.InternalTraceLevel, testEngine.InternalTraceLevel.ToString());

            if (options.ProcessModel != null)
            {
                model.PackageOverrides.Add(EnginePackageSettings.ProcessModel, options.ProcessModel);
            }
            if (options.DomainUsage != null)
            {
                model.PackageOverrides.Add(EnginePackageSettings.DomainUsage, options.DomainUsage);
            }
            if (options.MaxAgents >= 0)
            {
                model.PackageOverrides.Add(EnginePackageSettings.MaxAgents, options.MaxAgents);
            }
            if (options.RunAsX86)
            {
                model.PackageOverrides.Add(EnginePackageSettings.RunAsX86, true);
            }
            if (options.DebugAgent)
            {
                model.PackageOverrides.Add("DebugAgent", true);
            }

            return(model);
        }
Example #15
0
        public override void ApplySettings()
        {
            try
            {
                ConfigManager.OptionSection.Options["Options.InternalTraceLevel"].Value = traceLevelCombox.Text;
                ConfigManager.RefreshOptions();
                ConfigManager.Save();
            }
            catch (Exception ex)
            {
                throw new ApplicationException(Resources.SaveOptionsInternalTraceLevelFailure, ex);
            }

            InternalTraceLevel level = (InternalTraceLevel)Enum.Parse(InternalTraceLevel.Default.GetType(), traceLevelCombox.Text, true);

            InternalTrace.ReInitialize("CodeBuilder_%p.log", level);
        }
        public static void Main(string[] args)
        {
            var options = new AgentOptions(args);
            var pid     = Process.GetCurrentProcess().Id;
            var logName = $"testcentric-agent_{pid}.log";

            InternalTrace.Initialize(Path.Combine(options.WorkDirectory, logName), options.TraceLevel);
            log = InternalTrace.GetLogger(typeof(TestCentricAgent));

            if (options.DebugAgent || options.DebugTests)
            {
                TryLaunchDebugger();
            }

            LocateAgencyProcess(options.AgencyPid);

            log.Info($".NET 2.0 Agent process {pid} starting");
            log.Info($"  AgentId:   {options.AgentId}");
            log.Info($"  AgencyUrl: {options.AgencyUrl}");

            log.Info("Starting RemoteTestAgent");
            Agent           = new RemoteTestAgent(options.AgentId);
            Agent.Transport = new TestAgentRemotingTransport(Agent, options.AgencyUrl);

            try
            {
                if (Agent.Start())
                {
                    WaitForStop();
                }
                else
                {
                    log.Error("Failed to start RemoteTestAgent");
                    Environment.Exit(AgentExitCodes.FAILED_TO_START_REMOTE_AGENT);
                }
            }
            catch (Exception ex)
            {
                log.Error("Exception in RemoteTestAgent. {0}", ExceptionHelper.BuildMessageAndStackTrace(ex));
                Environment.Exit(AgentExitCodes.UNEXPECTED_EXCEPTION);
            }
            log.Info("Agent process {0} exiting cleanly", pid);

            Environment.Exit(AgentExitCodes.OK);
        }
Example #17
0
        private void InitializeInternalTrace()
        {
            var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), _options.InternalTraceLevel ?? "Off", true);

            if (traceLevel != InternalTraceLevel.Off)
            {
                var logName = GetLogFileName();

                StreamWriter streamWriter = null;
                if (traceLevel > InternalTraceLevel.Off)
                {
                    string logPath = Path.Combine(Directory.GetCurrentDirectory(), logName);
                    streamWriter           = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.Write));
                    streamWriter.AutoFlush = true;
                }
                InternalTrace.Initialize(streamWriter, traceLevel);
            }
        }
        public static NUnitForm nUnitGui_ShowGui(this API_NUnit_Gui nUnitGui, GuiOptions guiOptions)
        {
            "[API_NUnit_Gui] in nUnitGui_ShowGui".info();
            Func <NUnitForm> createNUnitForm =
                () => {
                var       sync      = new AutoResetEvent(false);
                NUnitForm nUnitForm = null;
                O2Thread.staThread(
                    () => {
                    if (NUnit.Util.Services.TestAgency.isNull())
                    {
                        var nunitGuiRunner = nUnitGui.Executable.parentFolder().pathCombine("lib\\nunit-gui-runner.dll");
                        nunitGuiRunner.loadAssemblyAndAllItsDependencies();

                        SettingsService settingsService = new SettingsService();
                        InternalTrace.Initialize("nunit-gui_%p.log", (InternalTraceLevel)settingsService.GetSetting("Options.InternalTraceLevel", InternalTraceLevel.Default));
                        ServiceManager.Services.AddService(settingsService);
                        ServiceManager.Services.AddService(new DomainManager());
                        ServiceManager.Services.AddService(new RecentFilesService());
                        ServiceManager.Services.AddService(new ProjectService());
                        ServiceManager.Services.AddService(new AddinRegistry());
                        ServiceManager.Services.AddService(new AddinManager());
                        ServiceManager.Services.AddService(new TestAgency());
                        ServiceManager.Services.InitializeServices();
                    }
                    else
                    {
                        "[API_NUnit_Gui] in nUnitGui_ShowGui: NUnit.Util.Services.TestAgency was not null: {0}".debug(NUnit.Util.Services.TestAgency);
                    }

                    ServiceManager.Services.AddService(new TestLoader(new GuiTestEventDispatcher()));
                    nUnitForm = new NUnitForm(guiOptions);
                    "NUnitForm".o2Cache(nUnitForm);
                    sync.Set();
                    nUnitForm.ShowDialog();
                    "NUnitForm".o2Cache(null);
                });
                sync.WaitOne();
                return(nUnitForm);
            };

            return("NUnitForm".o2Cache(createNUnitForm));
        }
Example #19
0
        /// <summary>
        /// Initialize the engine. This includes initializing mono addins,
        /// setting the trace level and creating the standard set of services
        /// used in the Engine.
        ///
        /// This interface is not normally called by user code. Programs linking
        /// only to the nunit.engine.api assembly are given a
        /// pre-initialized instance of TestEngine. Programs
        /// that link directly to nunit.engine usually do so
        /// in order to perform custom initialization.
        /// </summary>
        public void Initialize()
        {
#if NUNIT_ENGINE
            if (!AddinManager.IsInitialized)
            {
                // Pass in the current nunit.engine assembly because mono.addins uses the executing assembly by
                // default and that might be in a an entirely different directory than the runner that is using it.
                AddinManager.Initialize(Assembly.GetExecutingAssembly(), NUnitConfiguration.ApplicationDirectory);
                AddinManager.Registry.Update(null);
            }
#endif

            SettingsService settingsService = new SettingsService(true);

            if (InternalTraceLevel == InternalTraceLevel.Default)
            {
                InternalTraceLevel = settingsService.GetSetting("Options.InternalTraceLevel", InternalTraceLevel.Off);
            }

            if (InternalTraceLevel != InternalTraceLevel.Off)
            {
                var logName = string.Format("InternalTrace.{0}.log", Process.GetCurrentProcess().Id);
                InternalTrace.Initialize(Path.Combine(WorkDirectory, logName), InternalTraceLevel);
            }

            Services.Add(settingsService);
            Services.Add(new DomainManager());
            Services.Add(new DriverService());

#if NUNIT_ENGINE
            Services.Add(new RecentFilesService());
            Services.Add(new ProjectService());
            Services.Add(new RuntimeFrameworkService());
            Services.Add(new DefaultTestRunnerFactory());
            Services.Add(new TestAgency());
            Services.Add(new ResultService());
#else
            Services.Add(new CoreTestRunnerFactory());
#endif

            Services.ServiceManager.StartServices();
        }
Example #20
0
        /// <summary>
        /// Initialize the engine. This includes initializing mono addins,
        /// setting the trace level and creating the standard set of services
        /// used in the Engine.
        ///
        /// This interface is not normally called by user code. Programs linking
        /// only to the nunit.engine.api assembly are given a
        /// pre-initialized instance of TestEngine. Programs
        /// that link directly to nunit.engine usually do so
        /// in order to perform custom initialization.
        /// </summary>
        public void Initialize()
        {
            if (!AddinManager.IsInitialized)
            {
                AddinManager.Initialize(NUnitConfiguration.ApplicationDirectory);
                AddinManager.Registry.Update(null);

#if DEBUG
                Console.WriteLine("Addin Roots:");
                foreach (var root in AddinManager.Registry.GetAddinRoots())
                {
                    Console.WriteLine("   {0}", root.Name);
                }
#endif
            }

            SettingsService settingsService = new SettingsService(true);

            if (InternalTraceLevel == InternalTraceLevel.Default)
            {
                InternalTraceLevel = (InternalTraceLevel)settingsService.GetSetting("Options.InternalTraceLevel", InternalTraceLevel.Off);
            }

            if (InternalTraceLevel != InternalTraceLevel.Off)
            {
                var logName = string.Format("InternalTrace.{0}.log", Process.GetCurrentProcess().Id);
                InternalTrace.Initialize(Path.Combine(WorkDirectory, logName), InternalTraceLevel);
            }

            this.Services.Add(settingsService);
            this.Services.Add(new RecentFilesService());
            this.Services.Add(new DomainManager());
            this.Services.Add(new ProjectService());
            this.Services.Add(new RuntimeFrameworkSelector());
            this.Services.Add(new DefaultTestRunnerFactory());
            this.Services.Add(new DriverFactory());
            this.Services.Add(new TestAgency());
            this.Services.Add(new ResultService());

            this.Services.ServiceManager.InitializeServices();
        }
Example #21
0
        private void Initialize(string assemblyPath, IDictionary settings)
        {
            this.AssemblyPath = assemblyPath;
            this.Settings     = settings;

            if (settings.Contains(DriverSettings.InternalTraceLevel))
            {
                var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)settings[DriverSettings.InternalTraceLevel], true);

                if (settings.Contains(DriverSettings.InternalTraceWriter))
                {
                    InternalTrace.Initialize((TextWriter)settings[DriverSettings.InternalTraceWriter], traceLevel);
                }
                else
                {
                    var workDirectory = settings.Contains(DriverSettings.WorkDirectory) ? (string)settings[DriverSettings.WorkDirectory] : Environment.CurrentDirectory;
                    var logName       = string.Format(LOG_FILE_FORMAT, Process.GetCurrentProcess().Id, Path.GetFileName(assemblyPath));
                    InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
                }
            }
        }
        private void Initialize(string assemblyPath, IDictionary settings)
        {
            this.AssemblyPath = assemblyPath;
            this.Settings     = settings;

            if (settings.Contains("InternalTraceLevel"))
            {
                var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)settings["InternalTraceLevel"]);

                if (settings.Contains("InternalTraceWriter"))
                {
                    InternalTrace.Initialize((TextWriter)settings["InternalTraceWriter"], traceLevel);
                }
                else
                {
                    var workDirectory = settings.Contains("WorkDirectory") ? (string)settings["WorkDirectory"] : Environment.CurrentDirectory;
                    var logName       = string.Format("InternalTrace.{0}.{1}.log", Process.GetCurrentProcess().Id, Path.GetFileName(assemblyPath));
                    //var logName = string.Format("InternalTrace.{0}.log", Process.GetCurrentProcess().Id);
                    InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
                }
            }
        }
Example #23
0
        private void InitializeInternalTrace(NUnitLiteOptions _options)
        {
            var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), _options.InternalTraceLevel ?? "Off", true);

            if (traceLevel != InternalTraceLevel.Off)
            {
                var logName = GetLogFileName();

#if NETCF // NETCF: Try to encapsulate this
                InternalTrace.Initialize(Path.Combine(NUnit.Env.DocumentFolder, logName), traceLevel);
#else
                StreamWriter streamWriter = null;
                if (traceLevel > InternalTraceLevel.Off)
                {
                    string logPath = Path.Combine(Environment.CurrentDirectory, logName);
                    streamWriter           = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.Write));
                    streamWriter.AutoFlush = true;
                }
                InternalTrace.Initialize(streamWriter, traceLevel);
#endif
            }
        }
Example #24
0
        /// <summary>
        /// Initialize the engine. This includes initializing mono addins,
        /// setting the trace level and creating the standard set of services
        /// used in the Engine.
        ///
        /// This interface is not normally called by user code. Programs linking
        /// only to the nunit.engine.api assembly are given a
        /// pre-initialized instance of TestEngine. Programs
        /// that link directly to nunit.engine usually do so
        /// in order to perform custom initialization.
        /// </summary>
        public void Initialize()
        {
            if (InternalTraceLevel != InternalTraceLevel.Off && !InternalTrace.Initialized)
            {
                var logName = string.Format("InternalTrace.{0}.log", Process.GetCurrentProcess().Id);
                InternalTrace.Initialize(Path.Combine(WorkDirectory, logName), InternalTraceLevel);
            }

            Services.Add(new SettingsService(true));
            Services.Add(new DomainManager());
            Services.Add(new ExtensionService());
            Services.Add(new DriverService());
            Services.Add(new RecentFilesService());
            Services.Add(new ProjectService());
            Services.Add(new RuntimeFrameworkService());
            Services.Add(new DefaultTestRunnerFactory());
            Services.Add(new TestAgency());
            Services.Add(new ResultService());
            Services.Add(new TestFilterService());

            Services.ServiceManager.StartServices();
        }
Example #25
0
        private void InitializeInternalTrace(string assemblyPath, InternalTraceLevel traceLevel)
        {
            if (traceLevel != InternalTraceLevel.Off)
            {
#if !SILVERLIGHT
                var logName = string.Format(LOG_FILE_FORMAT, Process.GetCurrentProcess().Id, Path.GetFileName(assemblyPath));
#else
                var logName = string.Format(LOG_FILE_FORMAT, DateTime.Now.ToString("o"), Path.GetFileName(assemblyPath));
#endif
#if NETCF // NETCF: Try to encapsulate this
                InternalTrace.Initialize(Path.Combine(NUnit.Env.DocumentFolder, logName), traceLevel);
#else
                StreamWriter streamWriter = null;
                if (traceLevel > InternalTraceLevel.Off)
                {
                    string logPath = Path.Combine(Environment.CurrentDirectory, logName);
                    streamWriter           = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.Write));
                    streamWriter.AutoFlush = true;
                }
                InternalTrace.Initialize(streamWriter, traceLevel);
#endif
            }
        }
Example #26
0
        private void Initialize(string assemblyPath, IDictionary settings)
        {
            AssemblyNameOrPath = assemblyPath;
            Settings           = settings;

            if (settings.Contains(PackageSettings.InternalTraceLevel))
            {
                var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)settings[PackageSettings.InternalTraceLevel], true);

                if (settings.Contains(PackageSettings.InternalTraceWriter))
                {
                    InternalTrace.Initialize((TextWriter)settings[PackageSettings.InternalTraceWriter], traceLevel);
                }
#if !PORTABLE && !SILVERLIGHT
                else
                {
                    var workDirectory = settings.Contains(PackageSettings.WorkDirectory) ? (string)settings[PackageSettings.WorkDirectory] : Env.DefaultWorkDirectory;
                    var logName       = string.Format(LOG_FILE_FORMAT, Process.GetCurrentProcess().Id, Path.GetFileName(assemblyPath));
                    InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
                }
#endif
            }
        }
Example #27
0
        public static void Main(string[] args)
        {
            AgentId   = new Guid(args[0]);
            AgencyUrl = args[1];

            var traceLevel     = InternalTraceLevel.Off;
            var pid            = Process.GetCurrentProcess().Id;
            var debugArgPassed = false;
            var workDirectory  = string.Empty;
            var agencyPid      = string.Empty;

            for (int i = 2; i < args.Length; i++)
            {
                string arg = args[i];

                // NOTE: we can test these strings exactly since
                // they originate from the engine itself.
                if (arg == "--debug-agent")
                {
                    debugArgPassed = true;
                }
                else if (arg.StartsWith("--trace:"))
                {
                    traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), arg.Substring(8));
                }
                else if (arg.StartsWith("--pid="))
                {
                    agencyPid = arg.Substring(6);
                }
                else if (arg.StartsWith("--work="))
                {
                    workDirectory = arg.Substring(7);
                }
            }

            var logName = $"nunit-agent_{pid}.log";

            InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
            log = InternalTrace.GetLogger(typeof(NUnitTestAgent));

            if (debugArgPassed)
            {
                TryLaunchDebugger();
            }

            LocateAgencyProcess(agencyPid);

            log.Info("Agent process {0} starting", pid);
            log.Info("Running under version {0}, {1}",
                     Environment.Version,
                     RuntimeFramework.CurrentFramework.DisplayName);

            // Create CoreEngine
            var engine = new CoreEngine
            {
                WorkDirectory      = workDirectory,
                InternalTraceLevel = traceLevel
            };

            // Custom Service Initialization
            engine.Services.Add(new ExtensionService());
            engine.Services.Add(new DomainManager());
            engine.Services.Add(new InProcessTestRunnerFactory());
            engine.Services.Add(new DriverService());

            // Initialize Services
            log.Info("Initializing Services");
            engine.InitializeServices();

            log.Info("Starting RemoteTestAgent");
            Agent = new RemoteTestAgent(AgentId, AgencyUrl, engine.Services);

            try
            {
                if (Agent.Start())
                {
                    WaitForStop();
                }
                else
                {
                    log.Error("Failed to start RemoteTestAgent");
                    Environment.Exit(AgentExitCodes.FAILED_TO_START_REMOTE_AGENT);
                }
            }
            catch (Exception ex)
            {
                log.Error("Exception in RemoteTestAgent. {0}", ExceptionHelper.BuildMessageAndStackTrace(ex));
                Environment.Exit(AgentExitCodes.UNEXPECTED_EXCEPTION);
            }
            log.Info("Agent process {0} exiting cleanly", pid);

            Environment.Exit(AgentExitCodes.OK);
        }
Example #28
0
        public static int Main(string[] args)
        {
            ExtendedConsoleOptions options = new ExtendedConsoleOptions(args);

            // Create SettingsService early so we know the trace level right at the start
            SettingsService    settingsService = new SettingsService();
            InternalTraceLevel level           = (InternalTraceLevel)settingsService.GetSetting("Options.InternalTraceLevel", InternalTraceLevel.Default);

            if (options.trace != InternalTraceLevel.Default)
            {
                level = options.trace;
            }

            InternalTrace.Initialize("nunit-console_%p.log", level);

            log.Info("NUnit-console.exe starting");

            if (!options.nologo)
            {
                WriteCopyright();
            }

            if (options.help)
            {
                options.Help();
                return(ConsoleUi.OK);
            }

            if (options.NoArgs)
            {
                Console.Error.WriteLine("fatal error: no inputs specified");
                options.Help();
                return(ConsoleUi.OK);
            }

            if (!options.Validate())
            {
                foreach (string arg in options.InvalidArguments)
                {
                    Console.Error.WriteLine("fatal error: invalid argument: {0}", arg);
                }
                options.Help();
                return(ConsoleUi.INVALID_ARG);
            }

            // Add Standard Services to ServiceManager
            ServiceManager.Services.AddService(settingsService);
            ServiceManager.Services.AddService(new DomainManager());
            //ServiceManager.Services.AddService( new RecentFilesService() );
            ServiceManager.Services.AddService(new ProjectService());
            //ServiceManager.Services.AddService( new TestLoader() );
            ServiceManager.Services.AddService(new AddinRegistry());
            ServiceManager.Services.AddService(new AddinManager());
            ServiceManager.Services.AddService(new TestAgency());

            // Initialize Services
            ServiceManager.Services.InitializeServices();

            foreach (string parm in options.Parameters)
            {
                if (!Services.ProjectService.CanLoadProject(parm) && !PathUtils.IsAssemblyFileType(parm))
                {
                    Console.WriteLine("File type not known: {0}", parm);
                    return(ConsoleUi.INVALID_ARG);
                }
            }

            try
            {
                ExtendedConsoleUi consoleUi = new ExtendedConsoleUi();
                return(consoleUi.Execute(options));
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);
                return(ConsoleUi.FILE_NOT_FOUND);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unhandled Exception:\n{0}", ex.ToString());
                return(ConsoleUi.UNEXPECTED_ERROR);
            }
            finally
            {
                if (options.wait)
                {
                    Console.Out.WriteLine("\nHit <enter> key to continue");
                    Console.ReadLine();
                }

                log.Info("NUnit-console.exe terminating");
            }
        }
Example #29
0
        public static int Main(string[] args)
        {
            AgentId   = new Guid(args[0]);
            AgencyUrl = args[1];

            InternalTraceLevel traceLevel = InternalTraceLevel.Off;

            for (int i = 2; i < args.Length; i++)
            {
                string arg = args[i];

                // NOTE: we can test these strings exactly since
                // they originate from the engine itself.
                if (arg == "--debug-agent")
                {
                    if (!Debugger.IsAttached)
                    {
                        Debugger.Launch();
                    }
                }
                else if (arg.StartsWith("--trace:"))
                {
                    traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), arg.Substring(8));
                }
            }

            // Initialize trace so we can see what's happening
            int    pid     = Process.GetCurrentProcess().Id;
            string logname = string.Format(LOG_FILE_FORMAT, pid);

            InternalTrace.Initialize(logname, traceLevel);

            log.Info("Agent process {0} starting", pid);
            log.Info("Running under version {0}, {1}",
                     Environment.Version,
                     RuntimeFramework.CurrentFramework.DisplayName);

            // Restore the COMPLUS_Version env variable if it's been overridden by TestAgency::LaunchAgentProcess
            try
            {
                string cpvOriginal = Environment.GetEnvironmentVariable("TestAgency_COMPLUS_Version_Original");
                if (!string.IsNullOrEmpty(cpvOriginal))
                {
                    log.Debug("Agent process has the COMPLUS_Version environment variable value \"{0}\" overridden with \"{1}\", restoring the original value.", cpvOriginal, Environment.GetEnvironmentVariable("COMPLUS_Version"));
                    Environment.SetEnvironmentVariable("TestAgency_COMPLUS_Version_Original", null, EnvironmentVariableTarget.Process);                     // Erase marker
                    Environment.SetEnvironmentVariable("COMPLUS_Version", (cpvOriginal == "NULL" ? null : cpvOriginal), EnvironmentVariableTarget.Process); // Restore original (which might be n/a)
                }
            }
            catch (Exception ex)
            {
                log.Warning("Failed to restore the COMPLUS_Version variable. " + ex.Message); // Proceed with running tests anyway
            }

            // Create TestEngine - this program is
            // conceptually part of  the engine and
            // can access it's internals as needed.
            TestEngine engine = new TestEngine();

            // TODO: We need to get this from somewhere. Argument?
            engine.InternalTraceLevel = InternalTraceLevel.Debug;

            // Custom Service Initialization
            //log.Info("Adding Services");
            engine.Services.Add(new SettingsService(false));
            engine.Services.Add(new ExtensionService());
            engine.Services.Add(new ProjectService());
            engine.Services.Add(new DomainManager());
            engine.Services.Add(new InProcessTestRunnerFactory());
            engine.Services.Add(new DriverService());
            //engine.Services.Add( new TestLoader() );

            // Initialize Services
            log.Info("Initializing Services");
            engine.Initialize();

            Channel = ServerUtilities.GetTcpChannel();

            log.Info("Connecting to TestAgency at {0}", AgencyUrl);
            try
            {
                Agency = Activator.GetObject(typeof(ITestAgency), AgencyUrl) as ITestAgency;
            }
            catch (Exception ex)
            {
                log.Error("Unable to connect", ex);
            }

            if (Channel != null)
            {
                log.Info("Starting RemoteTestAgent");
                RemoteTestAgent agent = new RemoteTestAgent(AgentId, Agency, engine.Services);

                try
                {
                    if (agent.Start())
                    {
                        log.Debug("Waiting for stopSignal");
                        agent.WaitForStop();
                        log.Debug("Stop signal received");
                    }
                    else
                    {
                        log.Error("Failed to start RemoteTestAgent");
                    }
                }
                catch (Exception ex)
                {
                    log.Error("Exception in RemoteTestAgent", ex);
                }

                //log.Info("Unregistering Channel");
                try
                {
                    ChannelServices.UnregisterChannel(Channel);
                }
                catch (Exception ex)
                {
                    log.Error("ChannelServices.UnregisterChannel threw an exception", ex);
                }
            }

            log.Info("Agent process {0} exiting", Process.GetCurrentProcess().Id);

            return(0);
        }
Example #30
0
        public static void Main(string[] args)
        {
            AgentId   = new Guid(args[0]);
            AgencyUrl = args[1];

            InternalTraceLevel traceLevel = InternalTraceLevel.Off;
            int    pid            = Process.GetCurrentProcess().Id;
            bool   debugArgPassed = false;
            string workDirectory  = string.Empty;

            for (int i = 2; i < args.Length; i++)
            {
                string arg = args[i];

                // NOTE: we can test these strings exactly since
                // they originate from the engine itself.
                if (arg == "--debug-agent")
                {
                    debugArgPassed = true;
                }
                else if (arg.StartsWith("--trace:"))
                {
                    traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), arg.Substring(8));
                }
                else if (arg.StartsWith("--pid="))
                {
                    int agencyProcessId = int.Parse(arg.Substring(6));
                    AgencyProcess = Process.GetProcessById(agencyProcessId);
                }
                else if (arg.StartsWith("--work="))
                {
                    workDirectory = arg.Substring(7);
                }
            }

            var logName = $"nunit-agent_{pid}.log";

            InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
            log = InternalTrace.GetLogger(typeof(NUnitTestAgent));

            if (debugArgPassed)
            {
                TryLaunchDebugger();
            }

            log.Info("Agent process {0} starting", pid);
            log.Info("Running under version {0}, {1}",
                     Environment.Version,
                     RuntimeFramework.CurrentFramework.DisplayName);

            // Restore the COMPLUS_Version env variable if it's been overridden by TestAgency::LaunchAgentProcess
            try
            {
                string cpvOriginal = Environment.GetEnvironmentVariable("TestAgency_COMPLUS_Version_Original");
                if (!string.IsNullOrEmpty(cpvOriginal))
                {
                    log.Debug("Agent process has the COMPLUS_Version environment variable value \"{0}\" overridden with \"{1}\", restoring the original value.", cpvOriginal, Environment.GetEnvironmentVariable("COMPLUS_Version"));
                    Environment.SetEnvironmentVariable("TestAgency_COMPLUS_Version_Original", null, EnvironmentVariableTarget.Process);                     // Erase marker
                    Environment.SetEnvironmentVariable("COMPLUS_Version", (cpvOriginal == "NULL" ? null : cpvOriginal), EnvironmentVariableTarget.Process); // Restore original (which might be n/a)
                }
            }
            catch (Exception ex)
            {
                log.Warning("Failed to restore the COMPLUS_Version variable. " + ex.Message); // Proceed with running tests anyway
            }

            // Create TestEngine - this program is
            // conceptually part of  the engine and
            // can access it's internals as needed.
            TestEngine engine = new TestEngine();

            // TODO: We need to get this from somewhere. Argument?
            engine.InternalTraceLevel = InternalTraceLevel.Debug;

            // Custom Service Initialization
            //log.Info("Adding Services");
            engine.Services.Add(new SettingsService(false));
            engine.Services.Add(new ExtensionService());
            engine.Services.Add(new ProjectService());
            engine.Services.Add(new DomainManager());
            engine.Services.Add(new InProcessTestRunnerFactory());
            engine.Services.Add(new DriverService());

            // Initialize Services
            log.Info("Initializing Services");
            engine.Initialize();

            log.Info("Starting RemoteTestAgent");
            Agent = new RemoteTestAgent(AgentId, AgencyUrl, engine.Services);

            try
            {
                if (Agent.Start())
                {
                    WaitForStop();
                }
                else
                {
                    log.Error("Failed to start RemoteTestAgent");
                    Environment.Exit(AgentExitCodes.FAILED_TO_START_REMOTE_AGENT);
                }
            }
            catch (Exception ex)
            {
                log.Error("Exception in RemoteTestAgent", ex);
                Environment.Exit(AgentExitCodes.UNEXPECTED_EXCEPTION);
            }
            log.Info("Agent process {0} exiting cleanly", pid);

            Environment.Exit(AgentExitCodes.OK);
        }