Example #1
0
        public static void Action(Action action, IUnitTestGeneratorPackage package)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            try
            {
                action();
            }
            catch (InvalidOperationException ex)
            {
                VsShellUtilities.ShowMessageBox(
                    package,
                    ex.Message,
                    Constants.ExtensionName,
                    OLEMSGICON.OLEMSGICON_WARNING,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                VsShellUtilities.ShowMessageBox(
                    package,
                    string.Format(CultureInfo.CurrentCulture, "Exception raised\n{0}", ex),
                    Constants.ExtensionName,
                    OLEMSGICON.OLEMSGICON_CRITICAL,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }
        }
Example #2
0
        private static void CreateUnsavedFile(IUnitTestGeneratorPackage package, GenerationItem generationItem)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var tempFile = Path.Combine(Path.GetTempPath(), Path.GetFileName(generationItem.TargetFileName));

            try
            {
                File.WriteAllText(tempFile, Strings.DisconnectedFileHeader + generationItem.TargetContent);
                var dte = (DTE2)package.GetService(typeof(DTE));
                if (dte != null)
                {
                    var window = dte.ItemOperations.OpenFile(tempFile, Constants.vsViewKindCode);
                    window.Document.Saved = false;
                }
            }
            finally
            {
                try
                {
                    File.Delete(tempFile);
                }
                catch (IOException)
                {
                }
            }
        }
        /// <summary>
        /// Initializes the singleton instance of the command.
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public static async Task InitializeAsync(IUnitTestGeneratorPackage package)
        {
            _dte = (DTE2)await package.GetServiceAsync(typeof(DTE)).ConfigureAwait(true);

            OleMenuCommandService commandService = await package.GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(true) as OleMenuCommandService;

            _instance = new GoToUnitTestsCommand(package, commandService);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GenerateTestForSymbolCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file).
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        /// <param name="commandService">Command service to add command to, not null.</param>
        private GenerateTestForSymbolCommand(IUnitTestGeneratorPackage package, OleMenuCommandService commandService)
        {
            _package       = package ?? throw new ArgumentNullException(nameof(package));
            commandService = commandService ?? throw new ArgumentNullException(nameof(commandService));

            var menuCommandId             = new CommandID(CommandSet, CommandId);
            var regenerationMenuCommandId = new CommandID(CommandSet, RegenerateCommandId);

            var menuItem             = new OleMenuCommand(Execute, menuCommandId);
            var regenerationMenuItem = new OleMenuCommand(ExecuteRegeneration, regenerationMenuCommandId);

            menuItem.BeforeQueryStatus += (s, e) =>
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                var textView = GetTextView();

                var methodTask = package.JoinableTaskFactory.RunAsync(async() => await GetTargetSymbolAsync(textView).ConfigureAwait(true));
                var tuple      = methodTask.Join();
                var symbol     = tuple?.Item2;
                var baseType   = tuple?.Item3;
                menuItem.Visible             = false;
                regenerationMenuItem.Visible = false;
                if (symbol != null)
                {
                    menuItem.Visible             = true;
                    regenerationMenuItem.Visible = Keyboard.IsKeyDown(Key.LeftShift);
                    if (symbol.Kind == SymbolKind.NamedType)
                    {
                        menuItem.Text             = "Generate tests for type '" + symbol.Name + "'...";
                        regenerationMenuItem.Text = "Regenerate tests for type '" + symbol.Name + "'...";
                    }
                    else if (string.Equals(symbol.Name, ".ctor", StringComparison.OrdinalIgnoreCase))
                    {
                        menuItem.Text             = "Generate test for all constructors...";
                        regenerationMenuItem.Text = "Regenerate test for all constructors...";
                    }
                    else
                    {
                        menuItem.Text             = "Generate test for " + symbol.Kind.ToString().ToLower(CultureInfo.CurrentCulture) + " '" + symbol.Name + "'...";
                        regenerationMenuItem.Text = "Regenerate test for " + symbol.Kind.ToString().ToLower(CultureInfo.CurrentCulture) + " '" + symbol.Name + "'...";
                    }
                }
                else if (baseType.HasValue)
                {
                    if (InterfaceGenerationStrategyFactory.Supports(baseType.Value))
                    {
                        menuItem.Visible             = true;
                        regenerationMenuItem.Visible = Keyboard.IsKeyDown(Key.LeftShift);
                        menuItem.Text             = "Generate tests for base type '" + baseType.Value.Type.Name + "'...";
                        regenerationMenuItem.Text = "Regenerate tests for base type '" + baseType.Value.Type.Name + "'...";
                    }
                }
            };

            commandService.AddCommand(menuItem);
            commandService.AddCommand(regenerationMenuItem);
        }
Example #5
0
 private static void InstallPackage(Project currentProject, IUnitTestGeneratorPackage generatorPackage, INugetPackageReference package)
 {
     try
     {
         generatorPackage.PackageInstaller.InstallPackage("All", currentProject, package.Name, package.Version, false);
     }
     catch (InvalidOperationException)
     {
         generatorPackage.PackageInstaller.InstallPackage("https://www.nuget.org/api/v2/", currentProject, package.Name, package.Version, false);
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="GoToUnitTestsCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file).
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        /// <param name="commandService">Command service to add command to, not null.</param>
        private GoToUnitTestsCommand(IUnitTestGeneratorPackage package, OleMenuCommandService commandService)
        {
            _package       = package ?? throw new ArgumentNullException(nameof(package));
            commandService = commandService ?? throw new ArgumentNullException(nameof(commandService));

            var menuCommandId = new CommandID(CommandSet, CommandId);
            var menuItem      = new OleMenuCommand(Execute, menuCommandId);

            menuItem.BeforeQueryStatus += (s, e) =>
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                menuItem.Visible = SolutionUtilities.GetSelectedFiles(_dte, false, _package.Options.GenerationOptions).Any(ProjectItemModel.IsSupported);
            };

            commandService.AddCommand(menuItem);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GenerateUnitTestsCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file).
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        /// <param name="commandService">Command service to add command to, not null.</param>
        private GenerateUnitTestsCommand(IUnitTestGeneratorPackage package, OleMenuCommandService commandService)
        {
            _package       = package ?? throw new ArgumentNullException(nameof(package));
            commandService = commandService ?? throw new ArgumentNullException(nameof(commandService));

            var menuCommandId           = new CommandID(CommandSet, CommandId);
            var regenerateMenuCommandId = new CommandID(CommandSet, RegenerateCommandId);

            var menuItem           = new OleMenuCommand(Execute, menuCommandId);
            var regenerateMenuItem = new OleMenuCommand(ExecuteRegenerate, regenerateMenuCommandId);

            menuItem.BeforeQueryStatus += (s, e) =>
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                var itemVisible = IsAvailable;
                menuItem.Visible           = itemVisible;
                regenerateMenuItem.Visible = Keyboard.IsKeyDown(Key.LeftShift) && itemVisible;
            };

            commandService.AddCommand(menuItem);
            commandService.AddCommand(regenerateMenuItem);
        }
Example #8
0
        public static async Task ActionAsync(Func <Task> action, IUnitTestGeneratorPackage package)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            try
            {
                await action().ConfigureAwait(true);
            }
            catch (InvalidOperationException ex)
            {
                await package.JoinableTaskFactory.SwitchToMainThreadAsync();

                VsShellUtilities.ShowMessageBox(
                    package,
                    ex.Message,
                    Constants.ExtensionName,
                    OLEMSGICON.OLEMSGICON_WARNING,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                await package.JoinableTaskFactory.SwitchToMainThreadAsync();

                VsShellUtilities.ShowMessageBox(
                    package,
                    string.Format(CultureInfo.CurrentCulture, "Exception raised\n{0}", ex),
                    Constants.ExtensionName,
                    OLEMSGICON.OLEMSGICON_CRITICAL,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }
        }
Example #9
0
        public static async Task GenerateCodeAsync(IReadOnlyCollection <GenerationItem> generationItems, bool withRegeneration, IUnitTestGeneratorPackage package, Dictionary <Project, Tuple <HashSet <TargetAsset>, HashSet <IReferencedAssembly> > > requiredAssetsByProject, IMessageLogger messageLogger)
        {
            var solution = package.Workspace.CurrentSolution;
            var options  = package.Options;

            foreach (var generationItem in generationItems)
            {
                await GenerateItemAsync(withRegeneration, options, solution, generationItem).ConfigureAwait(true);
            }

            await package.JoinableTaskFactory.SwitchToMainThreadAsync();

            Attempt.Action(
                () =>
            {
                ThreadHelper.ThrowIfNotOnUIThread();

                messageLogger.LogMessage("Adding required assets to target project...");
                foreach (var pair in requiredAssetsByProject)
                {
                    AddTargetAssets(options, pair);

                    if (options.GenerationOptions.AddReferencesAutomatically)
                    {
                        ReferencesHelper.AddReferencesToProject(pair.Key, pair.Value.Item2.ToList(), messageLogger.LogMessage);
                    }
                }

                if (generationItems.All(x => string.IsNullOrWhiteSpace(x.TargetContent)))
                {
                    throw new InvalidOperationException("None of the selected targets contained a testable type. Tests can only be generated for classes and structs");
                }

                messageLogger.LogMessage("Adding generated items to target project...");
                foreach (var generationItem in generationItems.Where(x => !string.IsNullOrWhiteSpace(x.TargetContent)))
                {
                    if (generationItem.TargetProjectItems != null)
                    {
                        AddTargetItem(generationItems, options, generationItem);
                    }
                    else
                    {
                        CreateUnsavedFile(package, generationItem);
                    }
                }

                messageLogger.LogMessage("Generation complete.");
            }, package);
        }
Example #10
0
        public static void AddNugetPackagesToProject(Project currentProject, IList <INugetPackageReference> packagesToInstall, Action <string> logMessage, IUnitTestGeneratorPackage generatorPackage)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var installedPackages   = generatorPackage.PackageInstallerServices.GetInstalledPackages(currentProject).ToList();
            var installablePackages = packagesToInstall.Where(x => PackageNeedsInstalling(installedPackages, x)).ToList();

            if (generatorPackage.GetService(typeof(SVsThreadedWaitDialogFactory)) is IVsThreadedWaitDialogFactory dialogFactory)
            {
                dialogFactory.CreateInstance(out var dialog);
                if (dialog != null)
                {
                    foreach (var package in installablePackages)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, "Installing package '{0}'...", package.Name);
                        dialog.StartWaitDialog("Installing NuGet packages", message, string.Empty, null, message, 0, false, true);

                        InstallPackage(currentProject, generatorPackage, package);
                    }

                    dialog.EndWaitDialog(out _);
                    return;
                }
            }

            foreach (var package in installablePackages)
            {
                logMessage(string.Format(CultureInfo.CurrentCulture, "Installing package '{0}'...", package.Name));
                InstallPackage(currentProject, generatorPackage, package);
            }
        }