private static void TestNavigator( string code, Func <ITextStructureNavigator, SnapshotSpan, SnapshotSpan> func, int startPosition, int startLength, int endPosition, int endLength, CSharpParseOptions options) { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(code, options)) { var buffer = workspace.Documents.First().GetTextBuffer(); var provider = new TextStructureNavigatorProvider( workspace.GetService <ITextStructureNavigatorSelectorService>(), workspace.GetService <IContentTypeRegistryService>(), workspace.GetService <IWaitIndicator>()); var navigator = provider.CreateTextStructureNavigator(buffer); var actualSpan = func(navigator, new SnapshotSpan(buffer.CurrentSnapshot, startPosition, startLength)); var expectedSpan = new SnapshotSpan(buffer.CurrentSnapshot, endPosition, endLength); Assert.Equal(expectedSpan, actualSpan.Span); } }
public void TestCreateWithBufferNotInWorkspace() { // don't crash using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile("")) { var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); var contentTypeService = document.GetLanguageService <IContentTypeLanguageService>(); var contentType = contentTypeService.GetDefaultContentType(); var extraBuffer = workspace.ExportProvider.GetExportedValue <ITextBufferFactoryService>().CreateTextBuffer("", contentType); var waiter = new Waiter(); var provider = new SemanticClassificationTaggerProvider( workspace.ExportProvider.GetExportedValue <IForegroundNotificationService>(), workspace.ExportProvider.GetExportedValue <ISemanticChangeNotificationService>(), workspace.ExportProvider.GetExportedValue <ClassificationTypeMap>(), SpecializedCollections.SingletonEnumerable( new Lazy <IAsynchronousOperationListener, FeatureMetadata>( () => waiter, new FeatureMetadata(new Dictionary <string, object>() { { "FeatureName", FeatureAttribute.Classification } })))); using (var tagger = (AsynchronousTagger <IClassificationTag>)provider.CreateTagger <IClassificationTag>(extraBuffer)) { using (var edit = extraBuffer.CreateEdit()) { edit.Insert(0, "class A { }"); edit.Apply(); } waiter.CreateWaitTask().PumpingWait(); } } }
protected void VerifyCommitCharacters(string initialMarkup, string textTypedSoFar, char[] validChars, char[] invalidChars = null) { Assert.NotNull(validChars); invalidChars = invalidChars ?? new [] { 'x' }; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(initialMarkup)) { var hostDocument = workspace.DocumentWithCursor; var documentId = workspace.GetDocumentId(hostDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var position = hostDocument.CursorPosition.Value; var completionList = GetCompletionList(document, position, CompletionTriggerInfo.CreateInvokeCompletionTriggerInfo()); var item = completionList.Items.First(i => i.DisplayText.StartsWith(textTypedSoFar)); var completionService = document.Project.LanguageServices.GetService <ICompletionService>(); var completionRules = completionService.GetCompletionRules(); foreach (var ch in validChars) { Assert.True(completionRules.IsCommitCharacter(item, ch, textTypedSoFar), $"Expected '{ch}' to be a commit character"); } foreach (var ch in invalidChars) { Assert.False(completionRules.IsCommitCharacter(item, ch, textTypedSoFar), $"Expected '{ch}' NOT to be a commit character"); } } }
private static void AssertFormatAfterTypeChar(string code, string expected, Dictionary <OptionKey, object> changedOptionSet = null) { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(code)) { if (changedOptionSet != null) { var options = workspace.Options; foreach (var entry in changedOptionSet) { options = options.WithChangedOption(entry.Key, entry.Value); } workspace.Options = options; } var subjectDocument = workspace.Documents.Single(); var textUndoHistory = new Mock <ITextUndoHistoryRegistry>(); var editorOperationsFactory = new Mock <IEditorOperationsFactoryService>(); var editorOperations = new Mock <IEditorOperations>(); editorOperationsFactory.Setup(x => x.GetEditorOperations(subjectDocument.GetTextView())).Returns(editorOperations.Object); var commandHandler = new FormatCommandHandler(TestWaitIndicator.Default, textUndoHistory.Object, editorOperationsFactory.Object); var typedChar = subjectDocument.GetTextBuffer().CurrentSnapshot.GetText(subjectDocument.CursorPosition.Value - 1, 1); commandHandler.ExecuteCommand(new TypeCharCommandArgs(subjectDocument.GetTextView(), subjectDocument.TextBuffer, typedChar[0]), () => { }); var newSnapshot = subjectDocument.TextBuffer.CurrentSnapshot; Assert.Equal(expected, newSnapshot.GetText()); } }
public void TestSynchronousOutlining() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile("class Program {\r\n\r\n}")) { var tagProvider = new OutliningTaggerProvider( workspace.GetService <IForegroundNotificationService>(), workspace.GetService <ITextEditorFactoryService>(), workspace.GetService <IEditorOptionsFactoryService>(), workspace.GetService <IProjectionBufferFactoryService>(), (IEnumerable <Lazy <IAsynchronousOperationListener, FeatureMetadata> >)workspace.ExportProvider.GetExports <IAsynchronousOperationListener, FeatureMetadata>()); var document = workspace.Documents.First(); var textBuffer = document.TextBuffer; var tagger = tagProvider.CreateTagger <IOutliningRegionTag>(textBuffer); using (var disposable = (IDisposable)tagger) { ProducerPopulatedTagSource <IOutliningRegionTag> tagSource = null; tagProvider.TryRetrieveTagSource(null, textBuffer, out tagSource); tagSource.ComputeTagsSynchronouslyIfNoAsynchronousComputationHasCompleted = true; // The very first all to get tags should return the single outlining span. var tags = tagger.GetTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan())); Assert.Equal(1, tags.Count()); } } }
private void AssertTagsOnBracesOrSemicolonsTokens(string contents, int[] tokenIndices, CSharpParseOptions options = null) { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(contents, options)) { var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); var spans = new CSharpLineSeparatorService().GetLineSeparatorsAsync(document, document.GetSyntaxTreeAsync().Result.GetRoot().FullSpan, CancellationToken.None).Result; var tokens = document.GetCSharpSyntaxRootAsync(CancellationToken.None).Result.DescendantTokens().Where(t => t.Kind() == SyntaxKind.CloseBraceToken || t.Kind() == SyntaxKind.SemicolonToken); Assert.Equal(tokenIndices.Length, spans.Count()); int i = 0; foreach (var span in spans.OrderBy(t => t.Start)) { var expectedToken = tokens.ElementAt(tokenIndices[i]); var expectedSpan = expectedToken.Span; var message = string.Format("Expected to match curly {0} at span {1}. Actual span {2}", tokenIndices[i], expectedSpan, span); Assert.True(expectedSpan == span, message); ++i; } } }
public static Tuple <TestWorkspace, EnvDTE.FileCodeModel> CreateWorkspaceAndFileCodeModel(string file) { var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(file, exportProvider: VisualStudioTestExportProvider.ExportProvider); try { var project = workspace.CurrentSolution.Projects.Single(); var document = project.Documents.Single().Id; var componentModel = new MockComponentModel(workspace.ExportProvider); var serviceProvider = new MockServiceProvider(componentModel); var visualStudioWorkspaceMock = new MockVisualStudioWorkspace(workspace); var state = new CodeModelState(serviceProvider, project.LanguageServices, visualStudioWorkspaceMock); var codeModel = FileCodeModel.Create(state, null, document, new MockTextManagerAdapter()).Handle; return(Tuple.Create(workspace, (EnvDTE.FileCodeModel)codeModel)); } catch { // We threw during creation of the FileCodeModel. Make sure we clean up our workspace or else we leak it workspace.Dispose(); throw; } }
public void LargeNumberOfSpans() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(@"class Program { void M() { int z = 0; z = z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z; } }")) { var tagProducer = new TestTagProducer( (span, cancellationToken) => { return(new List <ITagSpan <TestTag> >() { new TagSpan <TestTag>(span, new TestTag()) }); }); var asyncListener = new TaggerOperationListener(); var notificationService = workspace.GetService <IForegroundNotificationService>(); var eventSource = CreateEventSource(); var taggerProvider = new TestTaggerProvider( tagProducer, eventSource, workspace, asyncListener, notificationService); var document = workspace.Documents.First(); var textBuffer = document.TextBuffer; var snapshot = textBuffer.CurrentSnapshot; var tagger = taggerProvider.CreateTagger <TestTag>(textBuffer); using (IDisposable disposable = (IDisposable)tagger) { var spans = Enumerable.Range(0, 101).Select(i => new Span(i * 4, 1)); var snapshotSpans = new NormalizedSnapshotSpanCollection(snapshot, spans); eventSource.SendUpdateEvent(); asyncListener.CreateWaitTask().PumpingWait(); var tags = tagger.GetTags(snapshotSpans); Assert.Equal(1, tags.Count()); } } }
public void TestWalker() { var text = @"class C : System.Exception { //Foo void Bar() { Console.WriteLine(1 + 1); } }"; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(text)) { var textBuffer = workspace.Documents.First().TextBuffer; var issueProducer = new CodeIssueTagProducer( TestWaitIndicator.Default, textBuffer, workspace.ExportProvider.GetExportedValue <CodeActionProviderManager>()); var snapshot = textBuffer.CurrentSnapshot; var tags1 = issueProducer.ProduceTagsAsync(snapshot.GetSpan(0, snapshot.Length), null, CancellationToken.None).PumpingWaitResult().ToList(); var tagCount1 = tags1.Count; Assert.True(tagCount1 > 0, tagCount1.ToString()); } }
public void TestGetFirstDiagnosticWithFixAsync() { var diagnosticService = new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); var fixers = CreateFixers(); var code = @" a "; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(code)) { var logger = SpecializedCollections.SingletonEnumerable(new Lazy <IErrorLoggerService>(() => workspace.Services.GetService <IErrorLoggerService>())); var fixService = new CodeFixService( diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable <Lazy <ISuppressionFixProvider, CodeChangeProviderMetadata> >()); var incrementalAnalzyer = (IIncrementalAnalyzerProvider)diagnosticService; // register diagnostic engine to solution crawler var analyzer = incrementalAnalzyer.CreateIncrementalAnalyzer(workspace); var reference = new MockAnalyzerReference(); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); var document = project.Documents.Single(); var unused = fixService.GetFirstDiagnosticWithFixAsync(document, TextSpan.FromBounds(0, 0), considerSuppressionFixes: false, cancellationToken: CancellationToken.None).Result; var fixer1 = fixers.Single().Value as MockFixer; var fixer2 = reference.Fixer as MockFixer; // check to make sure both of them are called. Assert.True(fixer1.Called); Assert.True(fixer2.Called); } }
public async Task TestGetTagsOnBufferTagger() { // don't crash using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile("class C { C c; }")) { var document = workspace.Documents.First(); var waiter = new Waiter(); var provider = new SemanticClassificationBufferTaggerProvider( workspace.ExportProvider.GetExportedValue <IForegroundNotificationService>(), workspace.ExportProvider.GetExportedValue <ISemanticChangeNotificationService>(), workspace.ExportProvider.GetExportedValue <ClassificationTypeMap>(), SpecializedCollections.SingletonEnumerable( new Lazy <IAsynchronousOperationListener, FeatureMetadata>( () => waiter, new FeatureMetadata(new Dictionary <string, object>() { { "FeatureName", FeatureAttribute.Classification } })))); var tagger = provider.CreateTagger <IClassificationTag>(document.TextBuffer); using (var disposable = (IDisposable)tagger) { await waiter.CreateWaitTask().ConfigureAwait(true); var tags = tagger.GetTags(document.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection()); var allTags = tagger.GetAllTags(document.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection(), CancellationToken.None); Assert.Empty(tags); Assert.NotEmpty(allTags); Assert.Equal(allTags.Count(), 1); } } }
public void TestEnter() { const string markup = @" class c { public int value {set; get; }} class d { void foo() { c foo = new c { v$$ } }"; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(markup)) { var hostDocument = workspace.Documents.Single(); var position = hostDocument.CursorPosition.Value; var document = workspace.CurrentSolution.GetDocument(hostDocument.Id); var triggerInfo = CompletionTriggerInfo.CreateTypeCharTriggerInfo('a'); var completionList = GetCompletionList(document, position, triggerInfo); var item = completionList.Items.First(); var completionService = document.Project.LanguageServices.GetService <ICompletionService>(); var completionRules = completionService.GetCompletionRules(); Assert.False(completionRules.SendEnterThroughToEditor(item, string.Empty, workspace.Options), "Expected false from SendEnterThroughToEditor()"); } }
protected void Check(string initial, string final, bool specialCaseSystem, CSharpParseOptions options = null) { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(initial)) { var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); var newRoot = OrganizeImportsService.OrganizeImportsAsync(document, specialCaseSystem).Result.GetSyntaxRootAsync().Result; Assert.Equal(final, newRoot.ToFullString()); } }
public EncapsulateFieldTestState(string markup) { Workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(markup, exportProvider: s_exportProvider); _testDocument = Workspace.Documents.Single(d => d.CursorPosition.HasValue || d.SelectedSpans.Any()); TargetDocument = Workspace.CurrentSolution.GetDocument(_testDocument.Id); var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback; var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => NotificationMessage = message); notificationService.NotificationCallback = callback; }
private void Test(string markup, string expectedText) { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(markup)) { var caret = workspace.Documents.First().CursorPosition; var service = new CSharpHelpContextService(); var actualText = service.GetHelpTermAsync(workspace.CurrentSolution.Projects.First().Documents.First(), workspace.Documents.First().SelectedSpans.First(), CancellationToken.None).WaitAndGetResult(CancellationToken.None); Assert.Equal(expectedText, actualText); } }
public void DiagnosticAnalyzerDriverIsSafeAgainstAnalyzerExceptions() { var source = TestResource.AllInOneCSharpCode; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(source, TestOptions.Regular)) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); ThrowingDiagnosticAnalyzer <SyntaxKind> .VerifyAnalyzerEngineIsSafeAgainstExceptions(analyzer => DiagnosticProviderTestUtilities.GetAllDiagnostics(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length), logAnalyzerExceptionAsDiagnostics: true)); } }
public GenerateTypeTestState( string initial, bool isLine, string projectToBeModified, string typeName, string existingFileName, string languageName) : this(projectToBeModified, typeName, existingFileName, languageName == LanguageNames.CSharp ? isLine ? CSharpWorkspaceFactory.CreateWorkspaceFromFile(initial, exportProvider : s_exportProvider) : CSharpWorkspaceFactory.CreateWorkspace(initial, exportProvider : s_exportProvider) : isLine ? VisualBasicWorkspaceFactory.CreateWorkspaceFromFile(initial, exportProvider : s_exportProvider) : VisualBasicWorkspaceFactory.CreateWorkspace(initial, exportProvider : s_exportProvider)) { }
public void TestSwitch() { var code = @" class C { void M(int variable) { switch (variable) { case 0: break; } } } "; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(code, parseOptions: Options.Script)) { var buffer = workspace.Documents.First().GetTextBuffer(); // At switch open paren var result = ProduceTags(workspace, buffer, 62); AssertEx.Equal(Enumerable(new Span(62, 1), new Span(71, 1)), result.Select(ts => ts.Span.Span).OrderBy(s => s.Start)); // After switch open paren result = ProduceTags(workspace, buffer, 83); Assert.True(result.IsEmpty()); // At switch close paren result = ProduceTags(workspace, buffer, 71); Assert.True(result.IsEmpty()); // After switch close paren result = ProduceTags(workspace, buffer, 72); AssertEx.Equal(Enumerable(new Span(62, 1), new Span(71, 1)), result.Select(ts => ts.Span.Span).OrderBy(s => s.Start)); // At switch open curly result = ProduceTags(workspace, buffer, 82); AssertEx.Equal(Enumerable(new Span(82, 1), new Span(138, 1)), result.Select(ts => ts.Span.Span).OrderBy(s => s.Start)); // After switch open curly result = ProduceTags(workspace, buffer, 83); Assert.True(result.IsEmpty()); // At switch close curly result = ProduceTags(workspace, buffer, 138); Assert.True(result.IsEmpty()); // After switch close curly result = ProduceTags(workspace, buffer, 139); AssertEx.Equal(Enumerable(new Span(82, 1), new Span(138, 1)), result.Select(ts => ts.Span.Span).OrderBy(s => s.Start)); } }
public async Task TestTagsChangedForEntireFile() { var code = @"class Program2 { string x = @""/// <summary>$$ /// </summary>""; }"; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(code)) { var document = workspace.Documents.First(); var subjectBuffer = document.TextBuffer; var checkpoint = new Checkpoint(); var tagComputer = new SyntacticClassificationTaggerProvider.TagComputer( subjectBuffer, workspace.GetService <IForegroundNotificationService>(), AggregateAsynchronousOperationListener.CreateEmptyListener(), typeMap: null, taggerProvider: new SyntacticClassificationTaggerProvider( notificationService: null, typeMap: null, viewSupportsClassificationServiceOpt: null, associatedViewService: null, allLanguageServices: ImmutableArray <Lazy <ILanguageService, LanguageServiceMetadata> > .Empty, contentTypes: ImmutableArray <Lazy <ILanguageService, ContentTypeLanguageMetadata> > .Empty, asyncListeners: ImmutableArray <Lazy <IAsynchronousOperationListener, FeatureMetadata> > .Empty), viewSupportsClassificationServiceOpt: null, associatedViewService: null, editorClassificationService: null, languageName: null); SnapshotSpan span = default(SnapshotSpan); tagComputer.TagsChanged += (s, e) => { span = e.Span; checkpoint.Release(); }; await checkpoint.Task.ConfigureAwait(true); checkpoint = new Checkpoint(); // Now apply an edit that require us to reclassify more that just the current line subjectBuffer.Insert(document.CursorPosition.Value, "\""); await checkpoint.Task.ConfigureAwait(true); Assert.Equal(subjectBuffer.CurrentSnapshot.Length, span.Length); } }
public void VerifyRefactoringDiabled(CodeRefactoringProvider codeRefactoring) { var refactoringService = new CodeRefactorings.CodeRefactoringService(GetMetadata(codeRefactoring)); using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(@"class Program {}")) { 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 = refactoringService.GetRefactoringsAsync(document, TextSpan.FromBounds(0, 0), CancellationToken.None).Result; Assert.True(extensionManager.IsDisabled(codeRefactoring)); Assert.False(extensionManager.IsIgnored(codeRefactoring)); } }
protected void VerifySendEnterThroughToEnter(string displayText, string textTypedSoFar, bool sendThroughEnterEnabled, bool expected) { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile("")) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); var item = new CSharpCompletionItem(workspace, CompletionProvider, displayText, new TextSpan(0, 0), null, null); var optionService = workspace.Services.GetService <IOptionService>(); var options = optionService.GetOptions().WithChangedOption(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord, sendThroughEnterEnabled); optionService.SetOptions(options); Assert.Equal(expected, CompletionProvider.SendEnterThroughToEditor(item, textTypedSoFar)); } }
private static TestWorkspace CreateWorkspaceFromFile(string source, string language, string rootNamespace) { if (language == LanguageNames.CSharp) { return(CSharpWorkspaceFactory.CreateWorkspaceFromFile(source)); } else { return(VisualBasicWorkspaceFactory.CreateWorkspaceFromFile( source, compilationOptions: new VisualBasic.VisualBasicCompilationOptions( OutputKind.DynamicallyLinkedLibrary, rootNamespace: rootNamespace))); } }
public CallHierarchyTestState(string markup, params Type[] additionalTypes) { var exportProvider = CreateExportProvider(additionalTypes); this.Workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(markup, exportProvider: exportProvider); var testDocument = Workspace.Documents.Single(d => d.CursorPosition.HasValue); _textView = testDocument.GetTextView(); _subjectBuffer = testDocument.GetTextBuffer(); var provider = Workspace.GetService <CallHierarchyProvider>(); _presenter = new MockCallHierarchyPresenter(); _commandHandler = new CallHierarchyCommandHandler(new[] { _presenter }, provider, TestWaitIndicator.Default); }
public void AnalyzerCreatedAtCompilationLevelNeedNotBeCompilationAnalyzer() { var source = @"x"; var analyzer = new CompilationAnalyzerWithSyntaxTreeAnalyzer(); using (var ideEngineWorkspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = DiagnosticProviderTestUtilities.GetAllDiagnostics(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == "SyntaxDiagnostic"); Assert.Equal(1, diagnosticsFromAnalyzer.Count()); } }
private static TestWorkspace ServiceSetup(CodeFixProvider codefix, out TestDiagnosticAnalyzerService diagnosticService, out CodeFixService fixService, out IErrorLoggerService errorLogger) { diagnosticService = new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); var fixers = SpecializedCollections.SingletonEnumerable( new Lazy <CodeFixProvider, CodeChangeProviderMetadata>( () => codefix, new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp))); var code = @"class Program { }"; var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(code); var logger = SpecializedCollections.SingletonEnumerable(new Lazy <IErrorLoggerService>(() => new TestErrorLogger())); errorLogger = logger.First().Value; fixService = new CodeFixService( diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable <Lazy <ISuppressionFixProvider, CodeChangeProviderMetadata> >()); return(workspace); }
public void TestOptionLoading() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile("")) { var optionService = workspace.GetService <IOptionService>(); var optionSet = optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, true); var serviceProvider = new MockServiceProvider(workspace.ExportProvider); using (var viewModel = new SpacingViewModel(optionSet, serviceProvider)) { // Use the first item's preview. var checkbox = viewModel.Items.OfType <CheckBoxOptionViewModel>().Where(c => c.Option == CSharpFormattingOptions.SpacingAfterMethodDeclarationName).First(); Assert.True(checkbox.IsChecked); } } }
private void VerifyExclusive(string markup, bool exclusive) { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(markup)) { var hostDocument = workspace.Documents.Single(); var position = hostDocument.CursorPosition.Value; var document = workspace.CurrentSolution.GetDocument(hostDocument.Id); var triggerInfo = CompletionTriggerInfo.CreateTypeCharTriggerInfo('a'); var completionList = GetCompletionList(document, position, triggerInfo); if (completionList != null) { Assert.True(exclusive == completionList.IsExclusive, "group.IsExclusive == " + completionList.IsExclusive); } } }
public CallHierarchyTestState(string markup, params Type[] additionalTypes) { var exportProvider = CreateExportProvider(additionalTypes); this.Workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(markup, exportProvider: exportProvider); var testDocument = Workspace.Documents.Single(d => d.CursorPosition.HasValue); _textView = testDocument.GetTextView(); _subjectBuffer = testDocument.GetTextBuffer(); var provider = Workspace.GetService<CallHierarchyProvider>(); var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback; var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => NotificationMessage = message); notificationService.NotificationCallback = callback; _presenter = new MockCallHierarchyPresenter(); _commandHandler = new CallHierarchyCommandHandler(new[] { _presenter }, provider, TestWaitIndicator.Default); }
public void DiagnosticAnalyzerDriverVsAnalyzerDriverOnCodeBlock() { var methodNames = new string[] { "Initialize", "AnalyzeCodeBlock" }; var source = @" [System.Obsolete] class C { int P { get; set; } delegate void A(); delegate string F(); } "; var ideEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var ideEngineWorkspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); DiagnosticProviderTestUtilities.GetAllDiagnostics(ideEngineAnalyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); foreach (var method in methodNames) { Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } var compilerEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var compilerEngineWorkspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result; compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { compilerEngineAnalyzer }); foreach (var method in methodNames) { Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } }
public void AnalyzerOptionsArePassedToAllAnalyzers() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(TestResource.AllInOneCSharpCode, TestOptions.Regular)) { var currentProject = workspace.CurrentSolution.Projects.Single(); var additionalDocId = DocumentId.CreateNewId(currentProject.Id); var newSln = workspace.CurrentSolution.AddAdditionalDocument(additionalDocId, "add.config", SourceText.From("random text")); currentProject = newSln.Projects.Single(); var additionalDocument = currentProject.GetAdditionalDocument(additionalDocId); AdditionalText additionalStream = new AdditionalTextDocument(additionalDocument.GetDocumentState()); AnalyzerOptions options = new AnalyzerOptions(ImmutableArray.Create(additionalStream)); var analyzer = new OptionsDiagnosticAnalyzer <SyntaxKind>(expectedOptions: options); var sourceDocument = currentProject.Documents.Single(); DiagnosticProviderTestUtilities.GetAllDiagnostics(analyzer, sourceDocument, new Text.TextSpan(0, sourceDocument.GetTextAsync().Result.Length)); analyzer.VerifyAnalyzerOptions(); } }