Exemplo n.º 1
0
        private void InitializeMainMenu()
        {
            _view.OnTestAssembliesLoaded();

            bool isTestRunning  = _model.IsTestRunning;
            bool canCloseOrSave = _model.HasTests && !isTestRunning;

            // File Menu
            _view.NewProjectCommand.Enabled  = !isTestRunning;
            _view.OpenProjectCommand.Enabled = !isTestRunning;
            _view.CloseCommand.Enabled       = canCloseOrSave;
            _view.SaveCommand.Enabled        = canCloseOrSave;
            _view.SaveAsCommand.Enabled      = canCloseOrSave;
            _view.SaveResultsCommand.Enabled = canCloseOrSave && _model.HasResults;
            _view.ReloadTestsCommand.Enabled = canCloseOrSave;
            _view.SelectRuntimeMenu.Enabled  = !isTestRunning && _runtimeSelectionController.AllowRuntimeSelection();
            _view.RecentProjectsMenu.Enabled = !isTestRunning;
            _view.ExitCommand.Enabled        = true;

            PopulateRecentProjectsMenu();

            _view.SelectRuntimeMenu.Popup += () => _runtimeSelectionController.PopulateMenu();

            // Project Menu
            _view.ProjectMenu.Enabled = _view.ProjectMenu.Visible = _model.HasTests;
        }
 public void PopulateMenu_WhenTestPackageIsNull_ThrowsInvalidOperationException()
 {
     Assert.Throws <InvalidOperationException>(() => _controller.PopulateMenu());
 }
Exemplo n.º 3
0
        private void WireUpEvents()
        {
            #region Model Events

            _model.Events.TestsLoading += (TestFilesLoadingEventArgs e) =>
            {
                UpdateViewCommands(testLoading: true);

                var message = e.TestFilesLoading.Count == 1 ?
                              $"Loading Assembly: {e.TestFilesLoading[0]}" :
                              $"Loading {e.TestFilesLoading.Count} Assemblies...";

                _longOpDisplay = _view.LongOperationDisplay(message);
            };

            _model.Events.TestLoaded += (TestNodeEventArgs e) =>
            {
                if (_longOpDisplay != null)
                {
                    _longOpDisplay.Dispose();
                    _longOpDisplay = null;
                }

                UpdateViewCommands();

                var files = _model.TestFiles;
                if (files.Count == 1)
                {
                    _view.SetTitleBar(files.First());
                }
            };

            _model.Events.TestsUnloading += (TestEventArgse) =>
            {
                UpdateViewCommands();
            };

            _model.Events.TestUnloaded += (TestEventArgs e) =>
            {
                _view.RunSummary.Text = null;

                UpdateViewCommands();
            };

            _model.Events.TestsReloading += (TestEventArgs e) =>
            {
                UpdateViewCommands();

                _longOpDisplay = _view.LongOperationDisplay("Reloading...");
            };

            _model.Events.TestReloaded += (TestNodeEventArgs e) =>
            {
                if (_longOpDisplay != null)
                {
                    _longOpDisplay.Dispose();
                    _longOpDisplay = null;
                }

                //SetTitleBar(TestProject.Name);

                if (_settings.Gui.ClearResultsOnReload)
                {
                    _view.RunSummary.Text = null;
                }

                UpdateViewCommands();
            };

            _model.Events.TestLoadFailure += (TestLoadFailureEventArgs e) =>
            {
                if (_longOpDisplay != null)
                {
                    _longOpDisplay.Dispose();
                }

                _view.MessageDisplay.Error(e.Exception.Message);
            };

            _model.Events.RunStarting += (RunStartingEventArgs e) =>
            {
                UpdateViewCommands();

                _view.RunSummary.Text = null;
            };

            _model.Events.RunFinished += (TestResultEventArgs e) =>
            {
                UpdateViewCommands();

                ResultSummary summary = ResultSummaryCreator.FromResultNode(e.Result);
                _view.RunSummary.Text = string.Format(
                    "Passed: {0}   Failed: {1}   Errors: {2}   Inconclusive: {3}   Invalid: {4}   Ignored: {5}   Skipped: {6}   Time: {7}",
                    summary.PassCount, summary.FailedCount, summary.ErrorCount, summary.InconclusiveCount, summary.InvalidCount, summary.IgnoreCount, summary.SkipCount, summary.Duration);

                if (summary.RunCount == 0)
                {
                }

                //string resultPath = Path.Combine(TestProject.BasePath, "TestResult.xml");
                // TODO: Use Work Directory
                string resultPath = "TestResult.xml";
                _model.SaveResults(resultPath);
                //try
                //{
                //    _model.SaveResults(resultPath);
                //    //log.Debug("Saved result to {0}", resultPath);
                //}
                //catch (Exception ex)
                //{
                //    //log.Warning("Unable to save result to {0}\n{1}", resultPath, ex.ToString());
                //}

                //if (e.Result.Outcome.Status == TestStatus.Failed)
                //    _view.Activate();

                // If we were running unattended, it's time to close
                if (_options.Unattended)
                {
                    _view.Close();
                }
            };

            _settings.Changed += (s, e) =>
            {
                if (e.SettingName == "Gui.Options.DisplayFormat")
                {
                    InitializeDisplay();
                }
            };

            _model.Events.UnhandledException += (UnhandledExceptionEventArgs e) =>
            {
                var display = new MessageDisplay("TestCentric - Internal Error");
                display.Error($"{e.Message}\n\n{e.StackTrace}");
            };

            #endregion

            #region View Events

            _view.Load += (s, e) =>
            {
                InitializeDisplay(_settings.Gui.DisplayFormat);

                var settings = _model.PackageOverrides;
                if (_options.ProcessModel != null)
                {
                    _view.ProcessModel.SelectedItem = _options.ProcessModel;
                }
                if (_options.DomainUsage != null)
                {
                    _view.DomainUsage.SelectedItem = _options.DomainUsage;
                }
                if (_options.MaxAgents >= 0)
                {
                    _model.Settings.Engine.Agents = _options.MaxAgents;
                }
                _view.RunAsX86.Checked = _options.RunAsX86;
            };

            _view.Shown += (s, e) =>
            {
                Application.DoEvents();

                // Load test specified on command line or
                // the most recent one if options call for it
                if (_options.InputFiles.Count != 0)
                {
                    LoadTests(_options.InputFiles);
                }
                else if (_settings.Gui.LoadLastProject && !_options.NoLoad)
                {
                    foreach (string entry in _recentFiles.Entries)
                    {
                        if (entry != null && File.Exists(entry))
                        {
                            LoadTests(entry);
                            break;
                        }
                    }
                }

                //if ( guiOptions.include != null || guiOptions.exclude != null)
                //{
                //    testTree.ClearSelectedCategories();
                //    bool exclude = guiOptions.include == null;
                //    string[] categories = exclude
                //        ? guiOptions.exclude.Split(',')
                //        : guiOptions.include.Split(',');
                //    if ( categories.Length > 0 )
                //        testTree.SelectCategories( categories, exclude );
                //}

                // Run loaded test automatically if called for
                if (_model.IsPackageLoaded && _options.RunAllTests)
                {
                    RunAllTests();
                }
                // Currently, --unattended without --run does nothing except exit.
                else if (_options.Unattended)
                {
                    _view.Close();
                }
            };

            _view.SplitterPositionChanged += (s, e) =>
            {
                _settings.Gui.MainForm.SplitPosition = _view.SplitterPosition;
            };

            _view.FormClosing += (s, e) =>
            {
                if (_model.IsPackageLoaded)
                {
                    if (_model.IsTestRunning)
                    {
                        DialogResult dialogResult = _view.MessageDisplay.Ask(
                            "A test is running, do you want to stop the test and exit?");

                        if (dialogResult == DialogResult.No)
                        {
                            e.Cancel = true;
                            return;
                        }

                        _model.CancelTestRun(true);
                    }

                    if (CloseProject() == DialogResult.Cancel)
                    {
                        e.Cancel = true;
                    }
                }

                if (!e.Cancel)
                {
                    if (_settings.Gui.DisplayFormat == "Mini")
                    {
                        _settings.Gui.MiniForm.Location = _view.Location;
                        _settings.Gui.MiniForm.Size     = _view.Size;
                    }
                    else
                    {
                        _settings.Gui.MainForm.Location = _view.Location;
                        _settings.Gui.MainForm.Size     = _view.Size;
                    }
                }
            };

            _view.RunButton.Execute  += () => RunSelectedTests();
            _view.StopButton.Execute += () => CancelRun();

            _view.FileMenu.Popup += () =>
            {
                bool isPackageLoaded = _model.IsPackageLoaded;
                bool isTestRunning   = _model.IsTestRunning;

                _view.OpenCommand.Enabled  = !isTestRunning;
                _view.CloseCommand.Enabled = isPackageLoaded && !isTestRunning;

                _view.ReloadTestsCommand.Enabled = isPackageLoaded && !isTestRunning;

                _view.RuntimeMenu.Visible = _model.AvailableRuntimes.Count > 1;

                _view.RecentFilesMenu.Enabled = !isTestRunning;

                //if (!isTestRunning)
                //{
                //    _recentProjectsMenuHandler.Load();
                //}
            };

            _view.RuntimeMenu.Popup += () => _runtimeSelectionController.PopulateMenu();

            _view.OpenCommand.Execute         += () => OpenProject();
            _view.CloseCommand.Execute        += () => CloseProject();
            _view.AddTestFilesCommand.Execute += () => AddTestFiles();
            _view.ReloadTestsCommand.Execute  += () => ReloadTests();

            _view.ProcessModel.SelectionChanged += () =>
            {
                ChangePackageSettingAndReload(EnginePackageSettings.ProcessModel, _view.ProcessModel.SelectedItem);
            };

            _view.DomainUsage.SelectionChanged += () =>
            {
                ChangePackageSettingAndReload(EnginePackageSettings.DomainUsage, _view.DomainUsage.SelectedItem);
            };

            _view.RunAsX86.CheckedChanged += () =>
            {
                var key = EnginePackageSettings.RunAsX86;
                if (_view.RunAsX86.Checked)
                {
                    ChangePackageSettingAndReload(key, true);
                }
                else
                {
                    ChangePackageSettingAndReload(key, null);
                }
            };

            _view.RecentFilesMenu.Popup += () =>
            {
                var menuItems = _view.RecentFilesMenu.MenuItems;
                // Test for null, in case we are running tests with a mock
                if (menuItems == null)
                {
                    return;
                }

                menuItems.Clear();
                int num = 0;
                foreach (string entry in _model.RecentFiles.Entries)
                {
                    var menuText = string.Format("{0} {1}", ++num, entry);
                    var menuItem = new MenuItem(menuText);
                    menuItem.Click += (sender, ea) =>
                    {
                        // HACK: We are loading new files, cancel any runtime override
                        _model.PackageOverrides.Remove(EnginePackageSettings.RequestedRuntimeFramework);
                        string path = ((MenuItem)sender).Text.Substring(2);
                        _model.LoadTests(new[] { path });
                    };
                    menuItems.Add(menuItem);
                    if (num >= _settings.Gui.RecentProjects.MaxFiles)
                    {
                        break;
                    }
                }
            };

            _view.ExitCommand.Execute += () => _view.Close();

            _view.DisplayFormat.SelectionChanged += () =>
            {
                _settings.Gui.DisplayFormat = _view.DisplayFormat.SelectedItem;
                InitializeDisplay(_view.DisplayFormat.SelectedItem);
            };

            _view.IncreaseFontCommand.Execute += () =>
            {
                applyFont(IncreaseFont(_settings.Gui.Font));
            };

            _view.DecreaseFontCommand.Execute += () =>
            {
                applyFont(DecreaseFont(_settings.Gui.Font));
            };

            _view.ChangeFontCommand.Execute += () =>
            {
                Font currentFont = _settings.Gui.Font;
                Font newFont     = _view.DialogManager.SelectFont(currentFont);
                if (newFont != _settings.Gui.Font)
                {
                    applyFont(newFont);
                }
            };

            _view.DialogManager.ApplyFont += (font) => applyFont(font);

            _view.RestoreFontCommand.Execute += () =>
            {
                applyFont(Form.DefaultFont);
            };

            _view.IncreaseFixedFontCommand.Execute += () =>
            {
                _settings.Gui.FixedFont = IncreaseFont(_settings.Gui.FixedFont);
            };

            _view.DecreaseFixedFontCommand.Execute += () =>
            {
                _settings.Gui.FixedFont = DecreaseFont(_settings.Gui.FixedFont);
            };

            _view.RestoreFixedFontCommand.Execute += () =>
            {
                _settings.Gui.FixedFont = new Font(FontFamily.GenericMonospace, 8.0f);
            };

            _view.StatusBarCommand.CheckedChanged += () =>
            {
                _view.StatusBarView.Visible = _view.StatusBarCommand.Checked;
            };

            _view.RunAllCommand.Execute      += () => RunAllTests();
            _view.RunSelectedCommand.Execute += () => RunSelectedTests();
            _view.RunFailedCommand.Execute   += () => RunFailedTests();

            _view.StopRunCommand.Execute        += () => CancelRun();
            _view.TestParametersCommand.Execute += () =>
            {
                using (var dlg = new TestParametersDialog())
                {
                    dlg.Font          = _settings.Gui.Font;
                    dlg.StartPosition = FormStartPosition.CenterParent;

                    if (_model.PackageOverrides.ContainsKey("TestParametersDictionary"))
                    {
                        var testParms = _model.PackageOverrides["TestParametersDictionary"] as IDictionary <string, string>;
                        foreach (string key in testParms.Keys)
                        {
                            dlg.Parameters.Add(key, testParms[key]);
                        }
                    }

                    if (dlg.ShowDialog(_view as IWin32Window) == DialogResult.OK)
                    {
                        ChangePackageSettingAndReload("TestParametersDictionary", dlg.Parameters);
                    }
                }
            };

            _view.ToolsMenu.Popup += () =>
            {
                _view.SaveResultsAsMenu.MenuItems.Clear();

                foreach (string format in _resultFormats)
                {
                    MenuItem formatItem = new MenuItem(format);
                    formatItem.Click += (s, e) => SaveResults(format);
                    _view.SaveResultsAsMenu.MenuItems.Add(formatItem);
                }
            };

            _view.SaveResultsCommand.Execute += () => SaveResults();

            _view.OpenWorkDirectoryCommand.Execute += () => System.Diagnostics.Process.Start(_model.WorkDirectory);

            _view.ExtensionsCommand.Execute += () =>
            {
                using (var extensionsDialog = new ExtensionDialog(_model.Services.ExtensionService))
                {
                    extensionsDialog.Font = _settings.Gui.Font;
                    extensionsDialog.ShowDialog();
                }
            };

            _view.SettingsCommand.Execute += () =>
            {
                SettingsDialog.Display(this, _model);
            };

            _view.TestCentricHelpCommand.Execute += () =>
            {
                _view.MessageDisplay.Error("Not Yet Implemented");
            };

            _view.NUnitHelpCommand.Execute += () =>
            {
                System.Diagnostics.Process.Start("https://github.com/nunit/docs/wiki/NUnit-Documentation");
            };

            _view.AboutCommand.Execute += () =>
            {
                using (AboutBox aboutBox = new AboutBox())
                {
                    aboutBox.ShowDialog();
                }
            };

            _view.ResultTabs.SelectionChanged += () =>
            {
                _settings.Gui.SelectedTab = _view.ResultTabs.SelectedIndex;
            };

            #endregion
        }