protected TestWorkspace CreateWorkspaceFromOptions(
            string initialMarkup, TestParameters parameters)
        {
            var workspace = TestWorkspace.IsWorkspaceElement(initialMarkup)
                 ? TestWorkspace.Create(initialMarkup, openDocuments: false)
                 : CreateWorkspaceFromFile(initialMarkup, parameters);

            workspace.ApplyOptions(parameters.options);

            return(workspace);
        }
Пример #2
0
        protected async Task <Tuple <Solution, Solution> > TestOperationsAsync(
            TestWorkspace workspace,
            string expectedText,
            ImmutableArray <CodeActionOperation> operations,
            ImmutableArray <TextSpan> conflictSpans,
            ImmutableArray <TextSpan> renameSpans,
            ImmutableArray <TextSpan> warningSpans,
            ImmutableArray <TextSpan> navigationSpans,
            DocumentId expectedChangedDocumentId,
            ParseOptions parseOptions = null)
        {
            var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
            var oldSolution    = appliedChanges.Item1;
            var newSolution    = appliedChanges.Item2;

            if (TestWorkspace.IsWorkspaceElement(expectedText))
            {
                await VerifyAgainstWorkspaceDefinitionAsync(expectedText, newSolution);

                return(Tuple.Create(oldSolution, newSolution));
            }

            var document = GetDocumentToVerify(expectedChangedDocumentId, oldSolution, newSolution);

            var fixedRoot = await document.GetSyntaxRootAsync();

            var actualText = fixedRoot.ToFullString();

            Assert.Equal(expectedText, actualText);

            TestAnnotations(conflictSpans, ConflictAnnotation.Kind);
            TestAnnotations(renameSpans, RenameAnnotation.Kind);
            TestAnnotations(warningSpans, WarningAnnotation.Kind);
            TestAnnotations(navigationSpans, NavigationAnnotation.Kind);

            return(Tuple.Create(oldSolution, newSolution));

            void TestAnnotations(ImmutableArray <TextSpan> expectedSpans, string annotationKind)
            {
                var annotatedItems = fixedRoot.GetAnnotatedNodesAndTokens(annotationKind).OrderBy(s => s.SpanStart).ToList();

                Assert.True(expectedSpans.Length == annotatedItems.Count,
                            $"Annotations of kind '{annotationKind}' didn't match. Expected: {expectedSpans.Length}. Actual: {annotatedItems.Count}.");

                for (var i = 0; i < Math.Min(expectedSpans.Length, annotatedItems.Count); i++)
                {
                    var actual   = annotatedItems[i].Span;
                    var expected = expectedSpans[i];
                    Assert.Equal(expected, actual);
                }
            }
        }
Пример #3
0
        public static GenerateTypeTestState Create(
            string initial,
            string projectToBeModified,
            string typeName,
            string existingFileName,
            string languageName)
        {
            var workspace = TestWorkspace.IsWorkspaceElement(initial)
                ? TestWorkspace.Create(initial, exportProvider: s_exportProvider)
                : languageName == LanguageNames.CSharp
                  ? TestWorkspace.CreateCSharp(initial, exportProvider: s_exportProvider)
                  : TestWorkspace.CreateVisualBasic(initial, exportProvider: s_exportProvider);

            return(new GenerateTypeTestState(projectToBeModified, typeName, existingFileName, workspace));
        }
Пример #4
0
        protected TestWorkspace CreateWorkspaceFromOptions(string workspaceMarkupOrCode, TestParameters parameters)
        {
            var composition = GetComposition().WithTestHostParts(parameters.testHost);

            parameters = SetParameterDefaults(parameters);

            var documentServiceProvider = GetDocumentServiceProvider();
            var workspace = TestWorkspace.IsWorkspaceElement(workspaceMarkupOrCode)
                ? TestWorkspace.Create(XElement.Parse(workspaceMarkupOrCode), openDocuments: false, composition: composition, documentServiceProvider: documentServiceProvider, workspaceKind: parameters.workspaceKind)
                : TestWorkspace.Create(GetLanguage(), parameters.compilationOptions, parameters.parseOptions, files: new[] { workspaceMarkupOrCode }, composition: composition, documentServiceProvider: documentServiceProvider, workspaceKind: parameters.workspaceKind);

#if !CODE_STYLE
            if (parameters.testHost == TestHost.OutOfProcess && _logger != null)
            {
                var remoteHostProvider = (InProcRemoteHostClientProvider)workspace.Services.GetRequiredService <IRemoteHostClientProvider>();
                remoteHostProvider.TraceListener = new XunitTraceListener(_logger);
            }
#endif
            InitializeWorkspace(workspace, parameters);

            // For CodeStyle layer testing, we create an .editorconfig at project root
            // to apply the options as workspace options are not available in CodeStyle layer.
            // Otherwise, we apply the options directly to the workspace.

#if CODE_STYLE
            // We need to ensure that our projects/documents are rooted for
            // execution from CodeStyle layer as we will be adding a rooted .editorconfig to each project
            // to apply the options.
            if (parameters.options != null)
            {
                MakeProjectsAndDocumentsRooted(workspace);
                AddAnalyzerConfigDocumentWithOptions(workspace, parameters.options);
            }
#else
            workspace.ApplyOptions(parameters.options);
#endif

            return(workspace);
        }
Пример #5
0
        protected async Task <Tuple <Solution, Solution> > TestOperationsAsync(
            TestWorkspace workspace,
            string expectedText,
            ImmutableArray <CodeActionOperation> operations,
            ImmutableArray <TextSpan> conflictSpans,
            ImmutableArray <TextSpan> renameSpans,
            ImmutableArray <TextSpan> warningSpans,
            ImmutableArray <TextSpan> navigationSpans,
            DocumentId expectedChangedDocumentId,
            ParseOptions parseOptions = null)
        {
            var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
            var oldSolution    = appliedChanges.Item1;
            var newSolution    = appliedChanges.Item2;

            if (TestWorkspace.IsWorkspaceElement(expectedText))
            {
                await VerifyAgainstWorkspaceDefinitionAsync(expectedText, newSolution);

                return(Tuple.Create(oldSolution, newSolution));
            }

            var document = GetDocumentToVerify(expectedChangedDocumentId, oldSolution, newSolution);

            var fixedRoot = await document.GetSyntaxRootAsync();

            var actualText = fixedRoot.ToFullString();

            // To help when a user just writes a test (and supplied no 'expectedText') just print
            // out the entire 'actualText' (without any trimming).  in the case that we have both,
            // call the normal Assert helper which will print out a good trimmed diff.
            if (expectedText == "")
            {
                Assert.Equal((object)expectedText, actualText);
            }
            else
            {
                Assert.Equal(expectedText, actualText);
            }

            TestAnnotations(conflictSpans, ConflictAnnotation.Kind);
            TestAnnotations(renameSpans, RenameAnnotation.Kind);
            TestAnnotations(warningSpans, WarningAnnotation.Kind);
            TestAnnotations(navigationSpans, NavigationAnnotation.Kind);

            return(Tuple.Create(oldSolution, newSolution));

            void TestAnnotations(ImmutableArray <TextSpan> expectedSpans, string annotationKind)
            {
                var annotatedItems = fixedRoot.GetAnnotatedNodesAndTokens(annotationKind).OrderBy(s => s.SpanStart).ToList();

                Assert.True(expectedSpans.Length == annotatedItems.Count,
                            $"Annotations of kind '{annotationKind}' didn't match. Expected: {expectedSpans.Length}. Actual: {annotatedItems.Count}.");

                for (var i = 0; i < Math.Min(expectedSpans.Length, annotatedItems.Count); i++)
                {
                    var actual   = annotatedItems[i].Span;
                    var expected = expectedSpans[i];
                    Assert.Equal(expected, actual);
                }
            }
        }
Пример #6
0
        internal async Task TestWithMockedGenerateTypeDialog(
            string initial,
            string languageName,
            string typeName,
            string expected             = null,
            bool isMissing              = false,
            Accessibility accessibility = Accessibility.NotApplicable,
            TypeKind typeKind           = TypeKind.Class,
            string projectName          = null,
            bool isNewFile              = false,
            string existingFilename     = null,
            ImmutableArray <string> newFileFolderContainers = default,
            string fullFilePath             = null,
            string newFileName              = null,
            string assertClassName          = null,
            bool checkIfUsingsIncluded      = false,
            bool checkIfUsingsNotIncluded   = false,
            string expectedTextWithUsings   = null,
            string defaultNamespace         = "",
            bool areFoldersValidIdentifiers = true,
            GenerateTypeDialogOptions assertGenerateTypeDialogOptions = null,
            IList <TypeKindOptions> assertTypeKindPresent             = null,
            IList <TypeKindOptions> assertTypeKindAbsent = null,
            bool isCancelled = false)
        {
            var workspace = TestWorkspace.IsWorkspaceElement(initial)
                ? TestWorkspace.Create(initial)
                : languageName == LanguageNames.CSharp
                  ? TestWorkspace.CreateCSharp(initial)
                  : TestWorkspace.CreateVisualBasic(initial);

            var testOptions = new TestParameters();

            var(diagnostics, actions, _) = await GetDiagnosticAndFixesAsync(workspace, testOptions);

            using var testState = new GenerateTypeTestState(workspace, projectToBeModified: projectName, typeName, existingFilename);

            // Initialize the viewModel values
            testState.TestGenerateTypeOptionsService.SetGenerateTypeOptions(
                accessibility: accessibility,
                typeKind: typeKind,
                typeName: testState.TypeName,
                project: testState.ProjectToBeModified,
                isNewFile: isNewFile,
                newFileName: newFileName,
                folders: newFileFolderContainers,
                fullFilePath: fullFilePath,
                existingDocument: testState.ExistingDocument,
                areFoldersValidIdentifiers: areFoldersValidIdentifiers,
                isCancelled: isCancelled);

            testState.TestProjectManagementService.SetDefaultNamespace(
                defaultNamespace: defaultNamespace);

            var generateTypeDiagFixes = diagnostics.SingleOrDefault(df => GenerateTypeTestState.FixIds.Contains(df.Id));

            if (isMissing)
            {
                Assert.Empty(actions);
                return;
            }

            var fixActions = MassageActions(actions);

            Assert.False(fixActions.IsDefault);

            // Since the dialog option is always fed as the last CodeAction
            var index  = fixActions.Count() - 1;
            var action = fixActions.ElementAt(index);

            Assert.Equal(action.Title, FeaturesResources.Generate_new_type);
            var operations = await action.GetOperationsAsync(CancellationToken.None);

            Tuple <Solution, Solution> oldSolutionAndNewSolution = null;

            if (!isNewFile)
            {
                oldSolutionAndNewSolution = await TestOperationsAsync(
                    testState.Workspace, expected, operations,
                    conflictSpans : ImmutableArray <TextSpan> .Empty,
                    renameSpans : ImmutableArray <TextSpan> .Empty,
                    warningSpans : ImmutableArray <TextSpan> .Empty,
                    navigationSpans : ImmutableArray <TextSpan> .Empty,
                    expectedChangedDocumentId : testState.ExistingDocument.Id);
            }
            else
            {
                oldSolutionAndNewSolution = await TestAddDocument(
                    testState.Workspace,
                    expected,
                    operations,
                    projectName != null,
                    testState.ProjectToBeModified.Id,
                    newFileFolderContainers,
                    newFileName);
            }

            if (checkIfUsingsIncluded)
            {
                Assert.NotNull(expectedTextWithUsings);
                await TestOperationsAsync(testState.Workspace, expectedTextWithUsings, operations,
                                          conflictSpans : ImmutableArray <TextSpan> .Empty,
                                          renameSpans : ImmutableArray <TextSpan> .Empty,
                                          warningSpans : ImmutableArray <TextSpan> .Empty,
                                          navigationSpans : ImmutableArray <TextSpan> .Empty,
                                          expectedChangedDocumentId : testState.InvocationDocument.Id);
            }

            if (checkIfUsingsNotIncluded)
            {
                var oldSolution        = oldSolutionAndNewSolution.Item1;
                var newSolution        = oldSolutionAndNewSolution.Item2;
                var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution);

                Assert.False(changedDocumentIds.Contains(testState.InvocationDocument.Id));
            }

            // Added into a different project than the triggering project
            if (projectName != null)
            {
                var appliedChanges   = ApplyOperationsAndGetSolution(testState.Workspace, operations);
                var newSolution      = appliedChanges.Item2;
                var triggeredProject = newSolution.GetProject(testState.TriggeredProject.Id);

                // Make sure the Project reference is present
                Assert.True(triggeredProject.ProjectReferences.Any(pr => pr.ProjectId == testState.ProjectToBeModified.Id));
            }

            // Assert Option Calculation
            if (assertClassName != null)
            {
                Assert.True(assertClassName == testState.TestGenerateTypeOptionsService.ClassName);
            }

            if (assertGenerateTypeDialogOptions != null || assertTypeKindPresent != null || assertTypeKindAbsent != null)
            {
                var generateTypeDialogOptions = testState.TestGenerateTypeOptionsService.GenerateTypeDialogOptions;

                if (assertGenerateTypeDialogOptions != null)
                {
                    Assert.True(assertGenerateTypeDialogOptions.IsPublicOnlyAccessibility == generateTypeDialogOptions.IsPublicOnlyAccessibility);
                    Assert.True(assertGenerateTypeDialogOptions.TypeKindOptions == generateTypeDialogOptions.TypeKindOptions);
                    Assert.True(assertGenerateTypeDialogOptions.IsAttribute == generateTypeDialogOptions.IsAttribute);
                }

                if (assertTypeKindPresent != null)
                {
                    foreach (var typeKindPresentEach in assertTypeKindPresent)
                    {
                        Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) != 0);
                    }
                }

                if (assertTypeKindAbsent != null)
                {
                    foreach (var typeKindPresentEach in assertTypeKindAbsent)
                    {
                        Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) == 0);
                    }
                }
            }
        }
Пример #7
0
 protected override TestWorkspace CreateWorkspaceFromFile(string initialMarkup, TestParameters parameters)
 {
     return(TestWorkspace.IsWorkspaceElement(initialMarkup)
         ? TestWorkspace.Create(initialMarkup)
         : TestWorkspace.CreateCSharp(initialMarkup, parameters.parseOptions, parameters.compilationOptions));
 }
 private static bool IsWorkspaceElement(string text)
 {
     return(TestWorkspace.IsWorkspaceElement(text));
 }
Пример #9
0
        protected async Task <Tuple <Solution, Solution> > TestOperationsAsync(
            TestWorkspace workspace,
            string expectedText,
            ImmutableArray <CodeActionOperation> operations,
            ImmutableArray <TextSpan> conflictSpans,
            ImmutableArray <TextSpan> renameSpans,
            ImmutableArray <TextSpan> warningSpans,
            bool ignoreTrivia,
            DocumentId expectedChangedDocumentId,
            ParseOptions parseOptions = null)
        {
            var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
            var oldSolution    = appliedChanges.Item1;
            var newSolution    = appliedChanges.Item2;

            if (TestWorkspace.IsWorkspaceElement(expectedText))
            {
                await VerifyAgainstWorkspaceDefinitionAsync(expectedText, newSolution);

                return(Tuple.Create(oldSolution, newSolution));
            }

            var document = GetDocumentToVerify(expectedChangedDocumentId, oldSolution, newSolution);

            var fixedRoot = await document.GetSyntaxRootAsync();

            var actualText = ignoreTrivia ? fixedRoot.ToString() : fixedRoot.ToFullString();

            if (ignoreTrivia)
            {
                TokenUtilities.AssertTokensEqual(expectedText, actualText, GetLanguage());
            }
            else
            {
                Assert.Equal(expectedText, actualText);
            }

            TestAnnotations(conflictSpans, ConflictAnnotation.Kind);
            TestAnnotations(renameSpans, RenameAnnotation.Kind);
            TestAnnotations(warningSpans, WarningAnnotation.Kind);

            return(Tuple.Create(oldSolution, newSolution));

            void TestAnnotations(ImmutableArray <TextSpan> expectedSpans, string annotationKind)
            {
                var annotatedTokens = fixedRoot.GetAnnotatedNodesAndTokens(annotationKind).Select(n => (SyntaxToken)n).ToList();

                Assert.Equal(expectedSpans.Length, annotatedTokens.Count);

                if (expectedSpans.Length > 0)
                {
                    var expectedTokens = TokenUtilities.GetTokens(TokenUtilities.GetSyntaxRoot(expectedText, GetLanguage(), parseOptions));
                    var actualTokens   = TokenUtilities.GetTokens(fixedRoot);

                    for (var i = 0; i < Math.Min(expectedTokens.Count, actualTokens.Count); i++)
                    {
                        var expectedToken = expectedTokens[i];
                        var actualToken   = actualTokens[i];

                        var actualIsConflict   = annotatedTokens.Contains(actualToken);
                        var expectedIsConflict = expectedSpans.Contains(expectedToken.Span);
                        Assert.Equal(expectedIsConflict, actualIsConflict);
                    }
                }
            }
        }
Пример #10
0
 protected override Task <TestWorkspace> CreateWorkspaceFromFileAsync(string definition, ParseOptions parseOptions, CompilationOptions compilationOptions)
 {
     return(TestWorkspace.IsWorkspaceElement(definition)
         ? TestWorkspace.CreateAsync(definition)
         : TestWorkspace.CreateCSharpAsync(definition, parseOptions, compilationOptions));
 }