public void IntroduceParameterRefactoring_MultipleVariablesInStatement_OnOneLine_MoveFirst()
        {
            //Input
            const string inputCode =
                @"Private Sub Foo(ByVal buz As Integer, _
ByRef baz As Date)
Dim bar As Boolean, bat As Date, bap As Integer
End Sub";

            //Expectation
            const string expectedCode =
                @"Private Sub Foo(ByVal buz As Integer, _
ByRef baz As Date, ByVal bar As Boolean)
Dim bat As Date, bap As Integer
End Sub";

            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "bar");

                var refactoring = TestRefactoring(rewritingManager, state);
                refactoring.Refactor(target);

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
        public void IntroduceFieldRefactoring_DisplaysInvalidSelectionAndDoesNothingForInvalidSelection()
        {
            //Input
            const string inputCode =
                @"Private fizz As Boolean

Private Sub Foo()
End Sub";
            var selection = new Selection(3, 16, 3, 16);

            IVBComponent component;
            var          vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

                var messageBox = new Mock <IMessageBox>();

                var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, messageBox.Object, rewritingManager);
                refactoring.Refactor(qualifiedSelection);

                messageBox.Verify(m => m.NotifyWarn(It.IsAny <string>(), It.IsAny <string>()), Times.Once);

                const string expectedCode = inputCode;
                var          actualCode   = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
        public void IntroduceFieldRefactoring_PassInTarget_Nonvariable()
        {
            //Input
            const string inputCode =
                @"Private Sub Foo()
Dim bar As Boolean
End Sub";

            IVBComponent component;
            var          vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var messageBox = new Mock <IMessageBox>();

                var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, messageBox.Object, rewritingManager);

                try
                {
                    refactoring.Refactor(state.AllUserDeclarations.First(d => d.DeclarationType != DeclarationType.Variable));
                }
                catch (ArgumentException e)
                {
                    messageBox.Verify(m => m.NotifyWarn(It.IsAny <string>(), It.IsAny <string>()), Times.Once);

                    Assert.AreEqual("target", e.ParamName);
                    var actual = component.CodeModule.Content();
                    Assert.AreEqual(inputCode, actual);
                    return;
                }

                Assert.Fail();
            }
        }
Example #4
0
        public void GivenPrivateSub_DefaultQuickFixRemovesParameter()
        {
            const string inputCode = @"
Private Sub Foo(ByVal arg1 as Integer)
End Sub";

            const string expectedCode = @"
Private Sub Foo()
End Sub";

            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var inspection        = new ParameterNotUsedInspection(state);
                var inspectionResults = inspection.GetInspectionResults(CancellationToken.None);
                var rewriteSession    = rewritingManager.CheckOutCodePaneSession();
                var selectionService  = MockedSelectionService();

                var factory = new Mock <IRefactoringPresenterFactory>().Object;
                var selectedDeclarationProvider = new SelectedDeclarationProvider(selectionService, state);
                var uiDispatcherMock            = new Mock <IUiDispatcher>();
                uiDispatcherMock
                .Setup(m => m.Invoke(It.IsAny <Action>()))
                .Callback((Action action) => action.Invoke());
                var refactoring = new RemoveParametersRefactoring(state, factory, rewritingManager, selectionService, selectedDeclarationProvider, uiDispatcherMock.Object);
                new RemoveUnusedParameterQuickFix(refactoring)
                .Fix(inspectionResults.First(), rewriteSession);
                Assert.AreEqual(expectedCode, component.CodeModule.Content());
            }
        }
Example #5
0
        public void ExtractInterfaceRefactoring_NullModel_NoChanges()
        {
            //Input
            const string inputCode =
                @"Private Sub Foo(ByVal arg1 As Integer, ByVal arg2 As String)
End Sub";
            var selection = new Selection(1, 23, 1, 27);

            IVBComponent component;
            var          vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out component, selection);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

                //Specify Params to remove
                var model = new ExtractInterfaceModel(state, qualifiedSelection);

                var presenter = new Mock <IExtractInterfacePresenter>();
                presenter.Setup(p => p.Show()).Returns(value: null);

                //SetupFactory
                var factory = SetupFactory(model);
                factory.Setup(f => f.Create()).Returns(presenter.Object);

                var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object, rewritingManager);
                refactoring.Refactor();

                Assert.AreEqual(1, vbe.Object.ActiveVBProject.VBComponents.Count());
                Assert.AreEqual(inputCode, component.CodeModule.Content());
            }
        }
Example #6
0
        private (string interfaceCode, string implementationCode) ApplyQuickFixToAppropriateInspectionResultsForImplementedInterface(
            string interfaceCode,
            string implementationCode,
            Func <RubberduckParserState, IInspection> inspectionFactory,
            Action <IQuickFix, IEnumerable <IInspectionResult>, IRewriteSession> applyQuickFix)
        {
            var(vbe, interfaceModuleName, implementationModuleName) = TestVbeForImplementedInterface(interfaceCode, implementationCode);

            var(state, rewriteManager) = MockParser.CreateAndParseWithRewritingManager(vbe);
            using (state)
            {
                var inspection        = inspectionFactory(state);
                var inspectionResults = InspectionResults(inspection, state);
                var rewriteSession    = rewriteManager.CheckOutCodePaneSession();

                var quickFix = QuickFix(state);

                applyQuickFix(quickFix, inspectionResults, rewriteSession);

                var actualInterfaceCode      = rewriteSession.CheckOutModuleRewriter(interfaceModuleName).GetText();
                var actualImplementationCode = rewriteSession.CheckOutModuleRewriter(implementationModuleName).GetText();

                return(actualInterfaceCode, actualImplementationCode);
            }
        }
        public void CanExecuteNameCollision_ActiveCodePane_EmptyClass()
        {
            var input   = @"
Sub Foo()
End Sub
";
            var builder = new MockVbeBuilder();
            var proj1   = builder.ProjectBuilder("TestProj1", ProjectProtection.Unprotected)
                          .AddComponent("Class1", ComponentType.ClassModule, input, Selection.Home)
                          .Build();
            var proj2 = builder.ProjectBuilder("TestProj2", ProjectProtection.Unprotected)
                        .AddComponent("Class1", ComponentType.ClassModule, string.Empty, Selection.Home)
                        .Build();

            var vbe = builder
                      .AddProject(proj1)
                      .AddProject(proj2)
                      .Build();

            vbe.Object.ActiveCodePane = proj1.Object.VBComponents[0].CodeModule.CodePane;
            if (string.IsNullOrEmpty(vbe.Object.ActiveCodePane.CodeModule.Content()))
            {
                Assert.Inconclusive("The active code pane should be the one with the method stub.");
            }

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager);
                Assert.IsTrue(extractInterfaceCommand.CanExecute(null));
            }
        }
Example #8
0
        public void MoveCloserToUsageRefactoring_ReferenceIsNotBeginningOfStatement_PassAsParam()
        {
            //Input
            const string inputCode =
                @"Private bar As Boolean
Private Sub Foo()
    Baz bar
End Sub
Sub Baz(ByVal bat As Boolean)
End Sub";

            const string expectedCode =
                @"Private Sub Foo()
    Dim bar As Boolean
    Baz bar
End Sub
Sub Baz(ByVal bat As Boolean)
End Sub";
            var selection = new Selection(1, 1);

            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

                var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager);
                refactoring.Refactor(qualifiedSelection);

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
Example #9
0
        public void MoveCloserToUsageRefactoring_ReferenceIsSeparatedWithColon()
        {
            //Input
            const string inputCode =
                @"Private bar As Boolean
Private Sub Foo(): Baz True, True, bar: End Sub
Private Sub Baz(ByVal bat As Boolean, ByVal bas As Boolean, ByVal bac As Boolean): End Sub";

            var selection = new Selection(1, 1);

            // Yeah, this code is a mess.  That is why we got the SmartIndenter
            const string expectedCode =
                @"Private Sub Foo(): Dim bar As Boolean
Baz True, True, bar: End Sub
Private Sub Baz(ByVal bat As Boolean, ByVal bas As Boolean, ByVal bac As Boolean): End Sub";

            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

                var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager);
                refactoring.Refactor(qualifiedSelection);

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
        public void IntroduceParameterRefactoring_PassInTarget()
        {
            //Input
            const string inputCode =
                @"Private Sub Foo()
Dim bar As Boolean
End Sub";

            //Expectation
            const string expectedCode =
                @"Private Sub Foo(ByVal bar As Boolean)
End Sub";

            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var refactoring = TestRefactoring(rewritingManager, state);

                var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "bar" && e.DeclarationType == DeclarationType.Variable);
                refactoring.Refactor(target);

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
        public void IntroduceParameterRefactoring_PassInTarget_Nonvariable()
        {
            //Input
            const string inputCode =
                @"Private Sub Foo()
Dim bar As Boolean
End Sub";

            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var messageBox = new Mock <IMessageBox>();

                var refactoring = TestRefactoring(rewritingManager, state, messageBox.Object);
                refactoring.Refactor(state.AllUserDeclarations.First(d => d.DeclarationType != DeclarationType.Variable));

                messageBox.Verify(m => m.NotifyWarn(It.IsAny <string>(), It.IsAny <string>()), Times.Once);

                const string expectedCode = inputCode;
                var          actualCode   = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
        public void IntroduceParameterRefactoring_NoParamsInList_Function()
        {
            //Input
            const string inputCode =
                @"Private Function Foo() As Boolean
Dim bar As Boolean
Foo = True
End Function";
            var selection = new Selection(2, 10, 2, 13);

            //Expectation
            const string expectedCode =
                @"Private Function Foo(ByVal bar As Boolean) As Boolean
Foo = True
End Function";

            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

                var refactoring = TestRefactoring(rewritingManager, state);
                refactoring.Refactor(qualifiedSelection);

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
        public void IntroduceParameterRefactoring_Properties_GetAndSet()
        {
            //Input
            const string inputCode =
                @"Property Get Foo(ByVal fizz As Boolean) As Variant
Dim bar As Integer
Foo = fizz
End Property

Property Set Foo(ByVal fizz As Boolean, ByVal buzz As Variant)
End Property";

            //Expectation
            const string expectedCode =
                @"Property Get Foo(ByVal fizz As Boolean, ByVal bar As Integer) As Variant
Foo = fizz
End Property

Property Set Foo(ByVal fizz As Boolean, ByVal bar As Integer, ByVal buzz As Variant)
End Property";

            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var refactoring = TestRefactoring(rewritingManager, state);

                var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "bar");
                refactoring.Refactor(target);

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
        public void IntroduceParameterRefactoring_DisplaysInvalidSelectionAndDoesNothingForInvalidSelection()
        {
            //Input
            const string inputCode =
                @"Private fizz As Boolean

Private Sub Foo()
End Sub";

            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var messageBox = new Mock <IMessageBox>();

                var refactoring = TestRefactoring(rewritingManager, state, messageBox.Object);

                var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "fizz");
                refactoring.Refactor(target);

                messageBox.Verify(m => m.NotifyWarn(It.IsAny <string>(), It.IsAny <string>()), Times.Once);

                const string expectedCode = inputCode;
                var          actualCode   = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
Example #15
0
        private string RewrittenForTargetRemovalCode(string inputCode, DeclarationType targetType, Func <Declaration, bool> targetCondition)
        {
            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out _).Object;

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe);
            using (state)
            {
                if (state.Status != ParserState.Ready)
                {
                    Assert.Inconclusive("Parser isn't ready. Test cannot proceed.");
                }

                var target = state.DeclarationFinder.UserDeclarations(targetType).SingleOrDefault(targetCondition);
                if (target == null)
                {
                    Assert.Inconclusive("No target was found in test code.");
                }

                var rewriteSession = rewritingManager.CheckOutCodePaneSession();
                var rewriter       = rewriteSession.CheckOutModuleRewriter(target.QualifiedModuleName);

                rewriter.Remove(target);

                return(rewriter.GetText());
            }
        }
Example #16
0
        public void MoveCloserToUsageRefactoring_Field_MultipleLines()
        {
            //Input
            const string inputCode =
                @"Private _
bar _
As _
Boolean
Private Sub Foo()
    bar = True
End Sub";
            var selection = new Selection(1, 1);

            //Expectation
            const string expectedCode =
                @"Private Sub Foo()
    Dim bar As Boolean
    bar = True
End Sub";

            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

                var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager);
                refactoring.Refactor(qualifiedSelection);

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
        public void MoveCloserToUsageRefactoring_TargetNotUserDefined()
        {
            //Input
            const string inputCode =
                @"Private Sub Foo()
    Dim baz As Excel.Range
    baz.Value = 42
End Sub";

            var vbe = new MockVbeBuilder()
                      .ProjectBuilder("TestProject", ProjectProtection.Unprotected)
                      .AddComponent("Module", ComponentType.StandardModule, inputCode)
                      .AddReference(ReferenceLibrary.Excel)
                      .AddProjectToVbeBuilder()
                      .Build()
                      .Object;

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe);
            using (state)
            {
                var target = state.DeclarationFinder.MatchName("Value")
                             .First(decl => decl.ParentDeclaration.IdentifierName == "Range");
                var testRefactoring = TestRefactoring(rewritingManager, state);

                Assert.Throws <TargetDeclarationNotUserDefinedException>(() =>
                                                                         testRefactoring.Refactor(target));

                var module           = state.DeclarationFinder.UserDeclarations(DeclarationType.ProceduralModule).Single(decl => decl.IdentifierName == "Module").QualifiedModuleName;
                var actualModuleCode = state.ProjectsProvider.Component(module).CodeModule.Content();

                Assert.AreEqual(inputCode, actualModuleCode);
            }
        }
Example #18
0
        public void IntroduceFieldRefactoring_InvalidSelection()
        {
            //Input
            const string inputCode =
                @"Private bar As Boolean
Private Sub Foo()
    bar = True
End Sub";
            var selection = new Selection(2, 15);

            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var messageBox = new Mock <IMessageBox>();

                var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

                var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, messageBox.Object, rewritingManager);
                refactoring.Refactor(qualifiedSelection);

                messageBox.Verify(m => m.NotifyWarn(It.IsAny <string>(), It.IsAny <string>()), Times.Once);

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(inputCode, actualCode);
            }
        }
Example #19
0
        public void ImplementInterface_PropertySet_AllTypes()
        {
            //Input
            const string inputCode1 =
                @"Public Sub Foo()
End Sub

Public Function Bar(ByVal a As Integer) As Boolean
End Function

Public Property Get Buz(ByVal a As Boolean) As Integer
End Property

Public Property Let Buz(ByVal a As Boolean, ByRef value As Integer)
End Property";

            const string inputCode2 =
                @"Implements Class1";

            //Expectation
            const string expectedCode =
                @"Implements Class1

Private Sub Class1_Foo()
    Err.Raise 5 'TODO implement interface member
End Sub

Private Function Class1_Bar(ByVal a As Integer) As Boolean
    Err.Raise 5 'TODO implement interface member
End Function

Private Property Get Class1_Buz(ByVal a As Boolean) As Integer
    Err.Raise 5 'TODO implement interface member
End Property

Private Property Let Class1_Buz(ByVal a As Boolean, ByRef value As Integer)
    Err.Raise 5 'TODO implement interface member
End Property
";

            var builder = new MockVbeBuilder();
            var project = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected)
                          .AddComponent("Class1", ComponentType.ClassModule, inputCode1)
                          .AddComponent("Class2", ComponentType.ClassModule, inputCode2)
                          .Build();
            var vbe       = builder.AddProject(project).Build();
            var component = project.Object.VBComponents[1];

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home);

                var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager);
                refactoring.Refactor(qualifiedSelection);

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
Example #20
0
        public void ExtractInterfaceRefactoring_NullPresenter_NoChanges()
        {
            //Input
            const string inputCode =
                @"Private Sub Foo(ByVal arg1 As Integer, ByVal arg2 As String)
End Sub";
            var selection = new Selection(1, 23, 1, 27);

            var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out var component, selection);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

                //SetupFactory
                var factory = new Mock <IRefactoringPresenterFactory>();
                factory.Setup(f => f.Create <IExtractInterfacePresenter, ExtractInterfaceModel>(It.IsAny <ExtractInterfaceModel>())).Returns(value: null);

                var selectionService = MockedSelectionService();

                var refactoring = TestRefactoring(rewritingManager, state, factory.Object, selectionService);

                Assert.Throws <InvalidRefactoringPresenterException>(() => refactoring.Refactor(qualifiedSelection));

                Assert.AreEqual(1, vbe.Object.ActiveVBProject.VBComponents.Count());
                Assert.AreEqual(inputCode, component.CodeModule.Content());
            }
        }
        private (IVBComponent component, IRewriteSession rewriteSession, RubberduckParserState state) TestSetup(string inputCode)
        {
            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component).Object;

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe);
            return(component, rewritingManager.CheckOutAttributesSession(), state);
        }
Example #22
0
        public void RecoveringAttributesRecoversTheAttributesInTheModulesProvided_ViaModule_PropertiesAreHandlesSeparately(string getAttributes, string letAttributes, string setAttributes)
        {
            var inputCode =
                $@"Public Property Get Foo() As Variant
{getAttributes}
End Property

Public Property Let Foo(ByVal RHS As Long)
{letAttributes}
End Property

Public Property Set Foo(ByVal RHs As Object)
{setAttributes}
End Property";

            var expectedCodeWithRecovery = inputCode;

            var expectedCodeWithoutRecovery =
                $@"Public Property Get Foo() As Variant{(string.IsNullOrEmpty(getAttributes) ? Environment.NewLine : string.Empty)}
End Property

Public Property Let Foo(ByVal RHS As Long){(string.IsNullOrEmpty(letAttributes) ? Environment.NewLine : string.Empty)}
End Property

Public Property Set Foo(ByVal RHs As Object){(string.IsNullOrEmpty(setAttributes) ? Environment.NewLine : string.Empty)}
End Property";

            var vbe = MockVbeBuilder.BuildFromStdModules(("RecoveryModule", inputCode), ("NoRecoveryModule", inputCode)).Object;

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe);
            using (state)
            {
                var attributesUpdater        = new AttributesUpdater(state);
                var mockFailureNotifier      = new Mock <IMemberAttributeRecoveryFailureNotifier>();
                var memberAttributeRecoverer = new MemberAttributeRecoverer(state, state, attributesUpdater, mockFailureNotifier.Object);
                memberAttributeRecoverer.RewritingManager = rewritingManager;

                var recoveryModule = state.DeclarationFinder.UserDeclarations(DeclarationType.Module)
                                     .First(decl => decl.IdentifierName.Equals("RecoveryModule")).QualifiedModuleName;
                var noRecoveryModule = state.DeclarationFinder.UserDeclarations(DeclarationType.Module)
                                       .First(decl => decl.IdentifierName.Equals("NoRecoveryModule")).QualifiedModuleName;

                var modulesToRecoverAttributesIn = new List <QualifiedModuleName> {
                    recoveryModule
                };

                memberAttributeRecoverer.RecoverCurrentMemberAttributesAfterNextParse(modulesToRecoverAttributesIn);

                var rewriteSession = rewritingManager.CheckOutCodePaneSession();
                var declarationsForWhichToRemoveAttributes = state.DeclarationFinder.UserDeclarations(DeclarationType.Property);
                RemoveAttributes(declarationsForWhichToRemoveAttributes, rewriteSession);

                ExecuteAndWaitForParserState(state, () => rewriteSession.TryRewrite(), ParserState.Ready);

                var actualCodeWithRecovery    = state.ProjectsProvider.Component(recoveryModule).CodeModule.Content();
                var actualCodeWithoutRecovery = state.ProjectsProvider.Component(noRecoveryModule).CodeModule.Content();
                Assert.AreEqual(expectedCodeWithRecovery, actualCodeWithRecovery);
                Assert.AreEqual(expectedCodeWithoutRecovery, actualCodeWithoutRecovery);
            }
        }
Example #23
0
        public void UseMeaningfulName_IgnoreQuickFixWorks()
        {
            const string inputCode =
                @"Sub Ffffff()
End Sub";

            const string expectedCode =
                @"'@Ignore UseMeaningfulName
Sub Ffffff()
End Sub";

            var builder = new MockVbeBuilder();
            var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected)
                          .AddComponent("MyClass", ComponentType.ClassModule, inputCode)
                          .Build();
            var component = project.Object.VBComponents[0];
            var vbe       = builder.AddProject(project).Build();

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var inspection        = new UseMeaningfulNameInspection(state, UseMeaningfulNameInspectionTests.GetInspectionSettings().Object);
                var inspectionResults = inspection.GetInspectionResults(CancellationToken.None);
                var rewriteSession    = rewritingManager.CheckOutCodePaneSession();

                new IgnoreOnceQuickFix(new AnnotationUpdater(), state, new[] { inspection }).Fix(inspectionResults.First(), rewriteSession);
                var actualCode = rewriteSession.CheckOutModuleRewriter(component.QualifiedModuleName).GetText();

                Assert.AreEqual(expectedCode, actualCode);
            }
        }
        public void AddNoIndentAnnotation_ModuleContainsCode()
        {
            var input =
                @"Option Explicit
Public Foo As Boolean

Sub Foo()
End Sub";

            var expected =
                @"'@NoIndent
Option Explicit
Public Foo As Boolean

Sub Foo()
End Sub";

            IVBComponent component;
            var          vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, Selection.Home);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var noIndentAnnotationCommand = MockIndenter.ArrangeNoIndentAnnotationCommand(vbe, state, rewritingManager);
                noIndentAnnotationCommand.Execute(null);

                Assert.AreEqual(expected, component.CodeModule.Content());
            }
        }
        public void IntroduceFieldRefactoring_MultipleVariablesInStatement_MoveSecond()
        {
            //Input
            const string inputCode = @"
Private Sub Foo(ByVal buz As Integer, _
ByRef baz As Date)
Dim bar As Boolean, _
bat As Date, _
bap As Integer
End Sub";
            //Expectation
            const string expectedCode = @"
Private bat As Date
Private Sub Foo(ByVal buz As Integer, _
ByRef baz As Date)
Dim bar As Boolean, _
bap As Integer
End Sub";

            IVBComponent component;
            var          vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "bat");

                var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, new Mock <IMessageBox>().Object, rewritingManager);
                refactoring.Refactor(target);

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
        private string ApplyQuickFixToFirstInspectionResultForImplicitWorksheetInspection(string inputCode)
        {
            var inputModule = ("Sheet1", inputCode, ComponentType.Document);
            var vbe         = MockVbeBuilder.BuildFromModules(inputModule, ReferenceLibrary.Excel).Object;

            var(state, rewriteManager) = MockParser.CreateAndParseWithRewritingManager(vbe);
            using (state)
            {
                var documentModule = state.DeclarationFinder.UserDeclarations(DeclarationType.Document)
                                     .OfType <DocumentModuleDeclaration>()
                                     .Single();
                documentModule.AddSupertypeName("Worksheet");

                var inspection        = new ImplicitContainingWorksheetReferenceInspection(state);
                var inspectionResults = inspection.GetInspectionResults(CancellationToken.None);

                var rewriteSession = rewriteManager.CheckOutCodePaneSession();

                var quickFix = QuickFix(state);

                var resultToFix = inspectionResults.First();
                quickFix.Fix(resultToFix, rewriteSession);

                var module = state.DeclarationFinder.AllModules.First(qmn => qmn.ComponentName == "Sheet1");

                return(rewriteSession.CheckOutModuleRewriter(module).GetText());
            }
        }
        public void IntroduceFieldRefactoring_PassInTarget()
        {
            //Input
            const string inputCode =
                @"Private Sub Foo()
Dim bar As Boolean
End Sub";
            var selection = new Selection(2, 10, 2, 13);

            //Expectation
            const string expectedCode =
                @"Private bar As Boolean
Private Sub Foo()
End Sub";

            IVBComponent component;
            var          vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

                var refactoring = new IntroduceFieldRefactoring((vbe.Object), state, null, rewritingManager);
                refactoring.Refactor(state.AllUserDeclarations.FindVariable(qualifiedSelection));

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
        private string ApplyQuickFixToAppropriateInspectionResults(
            IVBE vbe,
            string componentName,
            Func <RubberduckParserState, IInspection> inspectionFactory,
            Action <IQuickFix, IEnumerable <IInspectionResult>, IRewriteSession> applyQuickFix,
            CodeKind codeKind)
        {
            var(state, rewriteManager) = MockParser.CreateAndParseWithRewritingManager(vbe, documentModuleSupertypeNames: DefaultDocumentModuleSupertypeNames);
            using (state)
            {
                var inspection        = inspectionFactory(state);
                var inspectionResults = InspectionResults(inspection, state);
                var rewriteSession    = codeKind == CodeKind.AttributesCode
                    ? rewriteManager.CheckOutAttributesSession()
                    : rewriteManager.CheckOutCodePaneSession();

                var quickFix = QuickFix(state);

                applyQuickFix(quickFix, inspectionResults, rewriteSession);

                var module = state.DeclarationFinder.AllModules.First(qmn => qmn.ComponentName == componentName);

                return(rewriteSession.CheckOutModuleRewriter(module).GetText());
            }
        }
        public void IntroduceFieldRefactoring_OneFieldInList()
        {
            //Input
            const string inputCode =
                @"Public fizz As Integer
Private Sub Foo(ByVal buz As Integer)
Dim bar As Boolean
End Sub";
            var selection = new Selection(3, 10, 3, 13);

            //Expectation
            const string expectedCode =
                @"Public fizz As Integer
Private bar As Boolean
Private Sub Foo(ByVal buz As Integer)
End Sub";

            IVBComponent component;
            var          vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

                var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null, rewritingManager);
                refactoring.Refactor(qualifiedSelection);

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }
        public void IntroduceParameterRefactoring_MultipleVariablesInStatement_MoveFirst()
        {
            //Input
            const string inputCode =
                @"Private Sub Foo(ByVal buz As Integer, _
ByRef baz As Date)
Dim bar As Boolean, _
bat As Date, _
bap As Integer
End Sub";
            var selection = new Selection(3, 10, 3, 13);

            //Expectation
            const string expectedCode =
                @"Private Sub Foo(ByVal buz As Integer, _
ByRef baz As Date, ByVal bar As Boolean)
Dim bat As Date, _
bap As Integer
End Sub";   // note: the VBE removes extra spaces

            var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection);

            var(state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object);
            using (state)
            {
                var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

                var refactoring = TestRefactoring(rewritingManager, state);
                refactoring.Refactor(qualifiedSelection);

                var actualCode = component.CodeModule.Content();
                Assert.AreEqual(expectedCode, actualCode);
            }
        }