public void OrganizingCommandsDisabledInSubmission() { var exportProvider = ExportProviderCache .GetOrCreateExportProviderFactory(TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(InteractiveSupportsFeatureService.InteractiveTextBufferSupportsFeatureService))) .CreateExportProvider(); using (var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> class C { object $$goo; } </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, exportProvider: exportProvider)) { // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = new OrganizeDocumentCommandHandler(); var state = handler.GetCommandState(new SortAndRemoveUnnecessaryImportsCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); state = handler.GetCommandState(new OrganizeDocumentCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); } }
public void EncapsulateFieldCommandDisabledInSubmission() { var exportProvider = ExportProviderCache .GetOrCreateExportProviderFactory( TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(InteractiveTextBufferSupportsFeatureService))) .CreateExportProvider(); using (var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> class C { object $$goo; } </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, exportProvider: exportProvider)) { // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = new EncapsulateFieldCommandHandler(workspace.GetService <ITextBufferUndoManagerProvider>(), workspace.ExportProvider.GetExportedValue <IAsynchronousOperationListenerProvider>()); var state = handler.GetCommandState(new EncapsulateFieldCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); } }
protected static async Task AssertCodeCleanupResult(string expected, string code, bool systemUsingsFirst = true, bool separateUsingGroups = false) { var exportProvider = ExportProviderCache .GetOrCreateExportProviderFactory( TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(CodeCleanupAnalyzerProviderService))) .CreateExportProvider(); using var workspace = TestWorkspace.CreateCSharp(code, exportProvider: exportProvider); workspace.Options = workspace.Options.WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, systemUsingsFirst); workspace.Options = workspace.Options.WithChangedOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp, separateUsingGroups); // register this workspace to solution crawler so that analyzer service associate itself with given workspace var incrementalAnalyzerProvider = workspace.ExportProvider.GetExportedValue <IDiagnosticAnalyzerService>() as IIncrementalAnalyzerProvider; incrementalAnalyzerProvider.CreateIncrementalAnalyzer(workspace); var hostdoc = workspace.Documents.Single(); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var codeCleanupService = document.GetLanguageService <ICodeCleanupService>(); var enabledDiagnostics = codeCleanupService.GetAllDiagnostics(); var newDoc = await codeCleanupService.CleanupAsync( document, enabledDiagnostics, new ProgressTracker(), CancellationToken.None); var actual = await newDoc.GetTextAsync(); Assert.Equal(expected, actual.ToString()); }
public void ChangeSignatureCommandDisabledInSubmission() { var exportProvider = ExportProviderCache .GetOrCreateExportProviderFactory( TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(InteractiveSupportsFeatureService.InteractiveTextBufferSupportsFeatureService))) .CreateExportProvider(); using var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> class C { void M$$(int x) { } } </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, exportProvider: exportProvider); // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = new CSharpChangeSignatureCommandHandler(workspace.GetService <IThreadingContext>()); var state = handler.GetCommandState(new RemoveParametersCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); state = handler.GetCommandState(new ReorderParametersCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); }
internal static Lazy <IDynamicFileInfoProvider, FileExtensionsMetadata> GetDynamicFileInfoProvider() { var catalog = ExportProviderCache.CreateTypeCatalog(new Type[] { typeof(TestDynamicFileInfoProvider) }); var factory = ExportProviderCache.GetOrCreateExportProviderFactory(catalog); return(factory.CreateExportProvider().GetExport <IDynamicFileInfoProvider, FileExtensionsMetadata>()); }
private static IExportProviderFactory CreateExportProviderFactory() { var assemblies = TestExportProvider .GetCSharpAndVisualBasicAssemblies() .Concat(new[] { typeof(EditorServicesUtil).Assembly }); return(ExportProviderCache.GetOrCreateExportProviderFactory(ExportProviderCache.GetOrCreateAssemblyCatalog(assemblies, ExportProviderCache.CreateResolver()))); }
protected virtual ExportProvider GetExportProvider() { var requestHelperTypes = DesktopTestHelpers.GetAllTypesImplementingGivenInterface( typeof(IRequestHandler).Assembly, typeof(IRequestHandler)); var exportProviderFactory = ExportProviderCache.GetOrCreateExportProviderFactory( TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic .WithPart(typeof(LanguageServerProtocol)) .WithParts(requestHelperTypes)); return(exportProviderFactory.CreateExportProvider()); }
static ExportProvider GetExportProvider(AbstractKeywordHighlighterTests self) { IExportProviderFactory factory; lock (_specificHighlighterExportProviderFactories) { factory = _specificHighlighterExportProviderFactories.GetOrAdd( self.GetType(), type => ExportProviderCache.GetOrCreateExportProviderFactory(self.GetExportCatalog())); } return(factory.CreateExportProvider()); }
internal static ExportProvider GetExportProvider(IList <Type> excludedTypes, ComposableCatalog extraParts) { excludedTypes = excludedTypes ?? Type.EmptyTypes; if (excludedTypes.Count == 0 && (extraParts == null || extraParts.Parts.Count == 0)) { return(TestExportProvider.ExportProviderFactoryWithCSharpAndVisualBasic.CreateExportProvider()); } var baseCatalog = TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic; var filteredCatalog = baseCatalog.WithoutPartsOfTypes(excludedTypes); return(ExportProviderCache.GetOrCreateExportProviderFactory(filteredCatalog.WithParts(extraParts)).CreateExportProvider()); }
private static ExportProvider GetExportProvider(bool useMinimumCatalog, ComposableCatalog extraParts) { if (extraParts == null || extraParts.Parts.Count == 0) { return(useMinimumCatalog ? TestExportProvider.MinimumExportProviderFactoryWithCSharpAndVisualBasic.CreateExportProvider() : TestExportProvider.ExportProviderFactoryWithCSharpAndVisualBasic.CreateExportProvider()); } var baseCatalog = useMinimumCatalog ? TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic : TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic; return(ExportProviderCache.GetOrCreateExportProviderFactory(baseCatalog.WithParts(extraParts)).CreateExportProvider()); }
protected override ExportProvider GetExportProvider() { // Get all the liveshare request handlers in this assembly. var liveShareRequestHelperTypes = DesktopTestHelpers.GetAllTypesImplementingGivenInterface( typeof(LoadHandler).Assembly, typeof(ILspRequestHandler)); // Get all of the roslyn request helpers in M.CA.LanguageServer var roslynRequestHelperTypes = DesktopTestHelpers.GetAllTypesImplementingGivenInterface( typeof(RoslynHandlers.IRequestHandler).Assembly, typeof(RoslynHandlers.IRequestHandler)); var exportProviderFactory = ExportProviderCache.GetOrCreateExportProviderFactory( TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic .WithPart(typeof(MockDocumentNavigationServiceFactory)) .WithParts(liveShareRequestHelperTypes) .WithParts(roslynRequestHelperTypes)); return(exportProviderFactory.CreateExportProvider()); }
private static async Task VerifyRefactoringDisabledAsync <T>() where T : CodeRefactoringProvider { var exportProvider = ExportProviderCache.GetOrCreateExportProviderFactory(TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithPart(typeof(T))).CreateExportProvider(); using var workspace = TestWorkspace.CreateCSharp(@"class Program {}", exportProvider: exportProvider); var refactoringService = workspace.GetService <ICodeRefactoringService>(); var codeRefactoring = exportProvider.GetExportedValues <CodeRefactoringProvider>().OfType <T>().Single(); var project = workspace.CurrentSolution.Projects.Single(); var document = project.Documents.Single(); var extensionManager = document.Project.Solution.Workspace.Services.GetService <IExtensionManager>() as EditorLayerExtensionManager.ExtensionManager; var result = await refactoringService.GetRefactoringsAsync(document, TextSpan.FromBounds(0, 0), CancellationToken.None); Assert.True(extensionManager.IsDisabled(codeRefactoring)); Assert.False(extensionManager.IsIgnored(codeRefactoring)); }
public void OrderingOfEditorConfigMaintained() { using var tempRoot = new TempRoot(); var tempDirectory = tempRoot.CreateDirectory(); // Write out an .editorconfig. We'll write out 100 random GUIDs var expectedKeysInOrder = new List <string>(); using (var writer = new StreamWriter(tempDirectory.CreateFile(".editorconfig").Path)) { writer.WriteLine("root = true"); writer.WriteLine("[*.cs]"); for (int i = 0; i < 100; i++) { var key = Guid.NewGuid().ToString(); expectedKeysInOrder.Add(key); writer.WriteLine($"{key} = value"); } } // Create a workspace with a file in that path var codingConventionsCatalog = ExportProviderCache.GetOrCreateAssemblyCatalog(typeof(ICodingConventionsManager).Assembly).WithPart(typeof(MockFileWatcher)); var exportProvider = ExportProviderCache.GetOrCreateExportProviderFactory(TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(codingConventionsCatalog)).CreateExportProvider(); using var workspace = TestWorkspace.CreateWorkspace( new XElement("Workspace", new XElement("Project", new XAttribute("Language", "C#"), new XElement("Document", new XAttribute("FilePath", tempDirectory.CreateFile("Test.cs").Path)))), exportProvider: exportProvider); var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); var providerFactory = workspace.ExportProvider.GetExportedValues <IDocumentOptionsProviderFactory>().OfType <LegacyEditorConfigDocumentOptionsProviderFactory>().Single(); var provider = providerFactory.TryCreate(workspace); var option = new Option <List <string> >(nameof(LegacyEditorConfigDocumentOptionsProviderTests), nameof(OrderingOfEditorConfigMaintained), null, new[] { new KeysReturningStorageLocation() }); var optionKey = new OptionKey(option); // Fetch the underlying option order with a "option" that returns the keys provider.GetOptionsForDocumentAsync(document, CancellationToken.None).Result.TryGetDocumentOption(optionKey, workspace.Options, out object actualKeysInOrderObject); var actualKeysInOrder = Assert.IsAssignableFrom <IEnumerable <string> >(actualKeysInOrderObject); Assert.Equal(expectedKeysInOrder, actualKeysInOrder); }
public async Task UpdaterService() { var exportProvider = ExportProviderCache .GetOrCreateExportProviderFactory(ServiceTestExportProvider.CreateAssemblyCatalog() .WithParts(typeof(InProcRemoteHostClientProvider.Factory), typeof(CSharpOptionsSerializationService))) .CreateExportProvider(); using var workspace = new AdhocWorkspace(TestHostServices.CreateHostServices(exportProvider)); var options = workspace.CurrentSolution.Options .WithChangedOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1) .WithChangedOption(RemoteTestHostOptions.RemoteHostTest, true); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options)); var listenerProvider = exportProvider.GetExportedValue <AsynchronousOperationListenerProvider>(); var checksumUpdater = new SolutionChecksumUpdater(workspace, listenerProvider, CancellationToken.None); var service = workspace.Services.GetRequiredService <IRemoteHostClientProvider>(); // make sure client is ready using var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None); // add solution, change document workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default)); var project = workspace.AddProject("proj", LanguageNames.CSharp); var document = workspace.AddDocument(project.Id, "doc.cs", SourceText.From("code")); workspace.ApplyTextChanges(document.Id, new[] { new TextChange(new TextSpan(0, 1), "abc") }, CancellationToken.None); // wait for listener var workspaceListener = listenerProvider.GetWaiter(FeatureAttribute.Workspace); await workspaceListener.ExpeditedWaitAsync(); var listener = listenerProvider.GetWaiter(FeatureAttribute.SolutionChecksumUpdater); await listener.ExpeditedWaitAsync(); // checksum should already exist Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out _)); checksumUpdater.Shutdown(); }
public void SetProperty_MaxSupportedLangVersion(LanguageVersion?maxSupportedLangVersion) { var catalog = TestEnvironment.s_exportCatalog.Value .WithParts( typeof(CSharpParseOptionsChangingService)); var factory = ExportProviderCache.GetOrCreateExportProviderFactory(catalog); using var environment = new TestEnvironment(exportProviderFactory: factory); var hierarchy = environment.CreateHierarchy("CSharpProject", "Bin", projectRefPath: null, projectCapabilities: "CSharp"); var storage = Assert.IsAssignableFrom <IVsBuildPropertyStorage>(hierarchy); Assert.True(ErrorHandler.Succeeded( storage.SetPropertyValue( "MaxSupportedLangVersion", null, (uint)_PersistStorageType.PST_PROJECT_FILE, maxSupportedLangVersion?.ToDisplayString()))); _ = CSharpHelpers.CreateCSharpProject(environment, "Test", hierarchy); var project = environment.Workspace.CurrentSolution.Projects.Single(); var oldParseOptions = (CSharpParseOptions)project.ParseOptions; const LanguageVersion attemptedVersion = LanguageVersion.CSharp8; var canApply = environment.Workspace.CanApplyParseOptionChange( oldParseOptions, oldParseOptions.WithLanguageVersion(attemptedVersion), project); if (maxSupportedLangVersion.HasValue) { Assert.Equal(attemptedVersion <= maxSupportedLangVersion.Value, canApply); } else { Assert.True(canApply); } }
public Validator( string[] markedSource, ImmutableArray <ActiveStatementDebugInfo> activeStatements, ImmutableDictionary <ActiveMethodId, ImmutableArray <NonRemappableRegion> > nonRemappableRegions = null, Func <Solution, Solution> adjustSolution = null, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var exportProviderFactory = ExportProviderCache.GetOrCreateExportProviderFactory( TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic.WithPart(typeof(CSharpEditAndContinueAnalyzer.Factory)).WithPart(typeof(DummyLanguageService)).WithPart(typeof(TestActiveStatementSpanTrackerFactory))); var exportProvider = exportProviderFactory.CreateExportProvider(); Workspace = TestWorkspace.CreateCSharp(ActiveStatementsDescription.ClearTags(markedSource), exportProvider: exportProvider, openDocuments: true); if (adjustSolution != null) { Workspace.ChangeSolution(adjustSolution(Workspace.CurrentSolution)); } var solution = Workspace.CurrentSolution; var mockDebuggeModuleProvider = new Mock <IDebuggeeModuleMetadataProvider>(MockBehavior.Strict); var mockCompilationOutputsProvider = new Func <Project, CompilationOutputs>(_ => new MockCompilationOutputs(Guid.NewGuid())); var debuggingSession = new DebuggingSession(solution, mockCompilationOutputsProvider); if (initialState != CommittedSolution.DocumentState.None) { EditAndContinueWorkspaceServiceTests.SetDocumentsState(debuggingSession, solution, initialState); } debuggingSession.Test_SetNonRemappableRegions(nonRemappableRegions ?? ImmutableDictionary <ActiveMethodId, ImmutableArray <NonRemappableRegion> > .Empty); Assert.IsType <TestActiveStatementSpanTracker>(Workspace.Services.GetRequiredService <IActiveStatementSpanTrackerFactory>().GetOrCreateActiveStatementSpanTracker()); var telemetry = new EditSessionTelemetry(); EditSession = new EditSession(debuggingSession, telemetry, cancellationToken => Task.FromResult(activeStatements), mockDebuggeModuleProvider.Object); }
/// <summary> /// Assert the expected code value equals the actual processed input <paramref name="code"/>. /// </summary> /// <param name="expected">The actual processed code to verify against.</param> /// <param name="code">The input code to be processed and tested.</param> /// <param name="preferredImportPlacement">Indicates the code style option for the preferred 'using' directives placement.</param> /// <param name="systemUsingsFirst">Indicates whether <c><see cref="System"/>.*</c> '<c>using</c>' directives should preceed others. Default is <c>true</c>.</param> /// <param name="separateUsingGroups">Indicates whether '<c>using</c>' directives should be organized into separated groups. Default is <c>true</c>.</param> /// <returns>The <see cref="Task"/> to test code cleanup.</returns> private protected static async Task AssertCodeCleanupResult(string expected, string code, CodeStyleOption2 <AddImportPlacement> preferredImportPlacement, bool systemUsingsFirst = true, bool separateUsingGroups = false) { var exportProvider = ExportProviderCache.GetOrCreateExportProviderFactory(TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic).CreateExportProvider(); using var workspace = TestWorkspace.CreateCSharp(code, exportProvider: exportProvider); var solution = workspace.CurrentSolution .WithOptions(workspace.Options .WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, systemUsingsFirst) .WithChangedOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp, separateUsingGroups) .WithChangedOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredImportPlacement)) .WithAnalyzerReferences(new[] { new AnalyzerFileReference(typeof(CSharpCompilerDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile), new AnalyzerFileReference(typeof(UseExpressionBodyDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile) }); workspace.TryApplyChanges(solution); // register this workspace to solution crawler so that analyzer service associate itself with given workspace var incrementalAnalyzerProvider = workspace.ExportProvider.GetExportedValue <IDiagnosticAnalyzerService>() as IIncrementalAnalyzerProvider; incrementalAnalyzerProvider.CreateIncrementalAnalyzer(workspace); var hostdoc = workspace.Documents.Single(); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var codeCleanupService = document.GetLanguageService <ICodeCleanupService>(); var enabledDiagnostics = codeCleanupService.GetAllDiagnostics(); var newDoc = await codeCleanupService.CleanupAsync( document, enabledDiagnostics, new ProgressTracker(), CancellationToken.None); var actual = await newDoc.GetTextAsync(); Assert.Equal(expected, actual.ToString()); }
public async Task MoveToNamespace_WithoutOptionsService() { var code = @"namespace A[||] { class MyClass { void Method() { } } }"; var exportProviderWithoutOptionsService = ExportProviderCache.GetOrCreateExportProviderFactory( TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithoutPartsOfType(typeof(IMoveToNamespaceOptionsService))); using var workspace = CreateWorkspaceFromFile(code, new TestParameters(), exportProviderWithoutOptionsService); using var testState = new TestState(workspace); Assert.Null(testState.TestMoveToNamespaceOptionsService); var actions = await testState.MoveToNamespaceService.GetCodeActionsAsync( testState.InvocationDocument, testState.TestInvocationDocument.SelectedSpans.Single(), CancellationToken.None); Assert.Empty(actions); }
private static ExportProvider GetExportProvider() => ExportProviderCache .GetOrCreateExportProviderFactory(TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic) .CreateExportProvider();
protected override ExportProvider GetExportProvider() { return(ExportProviderCache .GetOrCreateExportProviderFactory(TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithPart(typeof(TestExperimentationService))) .CreateExportProvider()); }
static VisualStudioTestExportProvider() { Factory = ExportProviderCache.GetOrCreateExportProviderFactory( TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts( ExportProviderCache.GetOrCreateAssemblyCatalog(typeof(CSharpCodeModelService).Assembly))); }
public static ExportProvider CreateExportProvider() { return(ExportProviderCache .GetOrCreateExportProviderFactory(TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithPart(typeof(InProcRemoteHostClientFactory))) .CreateExportProvider()); }
public static ExportProvider CreateMinimalExportProvider() { return(ExportProviderCache .GetOrCreateExportProviderFactory(ServiceTestExportProvider.CreateAssemblyCatalog().WithPart(typeof(InProcRemoteHostClientFactory))) .CreateExportProvider()); }
private static IExportProviderFactory CreateExportProviderFactoryWithCSharpAndVisualBasic() { return(ExportProviderCache.GetOrCreateExportProviderFactory(EntireAssemblyCatalogWithCSharpAndVisualBasic)); }