Inheritance: RefactoringContext
		static LocalDeclarationSpaceVisitor GetVisitor(out TestRefactoringContext context, string input)
		{
			context = TestRefactoringContext.Create(input);
			var visitor = new LocalDeclarationSpaceVisitor();
			context.RootNode.AcceptVisitor(visitor);
			return visitor;
		}
        protected List <CodeAction> GetActions <T> (string input) where T : CodeActionProvider, new ()
        {
            var ctx = TestRefactoringContext.Create(input);

            ctx.FormattingOptions = formattingOptions;
            return(new T().GetActions(ctx).ToList());
        }
        protected void TestActionDescriptions(CodeActionProvider provider, string input, params string[] expected)
        {
            var ctx = TestRefactoringContext.Create(input);

            ctx.FormattingOptions = formattingOptions;
            var actions = provider.GetActions(ctx).ToList();

            Assert.AreEqual(
                expected,
                actions.Select(a => a.Description).ToArray());
        }
        protected static void TestWrongContext(ICodeActionProvider action, string input)
        {
            var  context = TestRefactoringContext.Create(input);
            bool isValid = action.GetActions(context).Any();

            if (!isValid)
            {
                Console.WriteLine("invalid node is:" + context.GetNode());
            }
            Assert.IsTrue(!isValid, action.GetType() + " shouldn't be valid there.");
        }
		protected static void CheckFix (TestRefactoringContext ctx, IEnumerable<CodeIssue> issues, string expectedOutput)
		{
			using (var script = ctx.StartScript ()) {
				foreach (var issue in issues) {
					issue.Actions.First ().Run (script);
				}
			}
			bool pass = expectedOutput == ctx.Text;
			if (!pass) {
				Console.WriteLine (ctx.Text);
			}
			Assert.AreEqual (expectedOutput, ctx.Text);
		}
        protected static string RunContextAction(ICodeActionProvider action, string input, int actionIndex = 0)
        {
            var  context = TestRefactoringContext.Create(input);
            bool isValid = action.GetActions(context).Any();

            if (!isValid)
            {
                Console.WriteLine("invalid node is:" + context.GetNode());
            }
            Assert.IsTrue(isValid, action.GetType() + " is invalid.");
            using (var script = context.StartScript()) {
                action.GetActions(context).Skip(actionIndex).First().Run(script);
            }

            return(context.doc.Text);
        }
Exemple #7
0
        public void TestBug10671()
        {
            var input = @"
namespace TestConsole
{
    public class Test : $BaseMissing
    {
    }
}
";
            // action allowed to create a nested class
            var context = TestRefactoringContext.Create(input, false);
            var actions = new CreateClassDeclarationAction().GetActions(context);

            Assert.AreEqual(1, actions.Count());
        }
Exemple #8
0
        public void TestAddBaseTypeGenerics()
        {
            var context = TestRefactoringContext.Create(@"
public class $Foo<T> where T : new()
{
}");

            using (var script = context.StartScript()) {
                var type = context.GetNode <TypeDeclaration>();
                script.ChangeBaseTypes(type, new AstType[] { AstType.Create("System.Test") });
            }

            Assert.AreEqual(@"
public class Foo<T> : System.Test where T : new()
{
}", context.Text);
        }
Exemple #9
0
        public void TestRemoveBaseType()
        {
            var context = TestRefactoringContext.Create(@"
public class $Foo : System.IDisposable
{
}");

            using (var script = context.StartScript()) {
                var type = context.GetNode <TypeDeclaration>();
                script.ChangeBaseTypes(type, Enumerable.Empty <AstType>());
            }

            Assert.AreEqual(@"
public class Foo
{
}", context.Text);
        }
Exemple #10
0
        public void TestReplaceBaseType()
        {
            var context = TestRefactoringContext.Create(@"
public class $Foo : System.IDisposable
{
}");

            using (var script = context.StartScript()) {
                var type = context.GetNode <TypeDeclaration>();
                script.ChangeBaseTypes(type, new AstType[] { AstType.Create("System.Test") });
            }

            Assert.AreEqual(@"
public class Foo : System.Test
{
}", context.Text);
        }
Exemple #11
0
        public void TestRenameInterfaceMethod()
        {
            List <string> contents = new List <string>()
            {
                @"interface ITest1
{
	int $method ();
}
class Test2 : ITest1
{
	int method ()
	{
	}
}", @"class Test3 : ITest1
{
	int method ()
	{
	}
}"
            };
            var context = TestRefactoringContext.Create(contents, 0);

            using (var script = context.StartScript()) {
                var method = context.GetNode <MethodDeclaration>();
                script.Rename(((MemberResolveResult)context.Resolve(method)).Member, "newName");
            }

            Assert.AreEqual(@"interface ITest1
{
	int newName ();
}
class Test2 : ITest1
{
	int newName ()
	{
	}
}", context.GetSideDocumentText(0));

            Assert.AreEqual(@"class Test3 : ITest1
{
	int newName ()
	{
	}
}", context.GetSideDocumentText(1));
        }
Exemple #12
0
        public void TestGlobalOperation()
        {
            List <string> contents = new List <string>()
            {
                @"class Test1
{
	public int $x;
}", @"class Test2
{
	public void Foo(Test1 test1)
	{
		test1.x = 1;
		test1.x = 2;
	}
}"
            };
            var context = TestRefactoringContext.Create(contents, 0);

            using (var script = context.StartScript()) {
                var variable = context.GetNode <VariableInitializer>();
                script.DoGlobalOperationOn(new List <IEntity>()
                {
                    ((MemberResolveResult)context.Resolve(variable)).Member
                }, (rCtx, rScript, nodes) => {
                    foreach (var node in nodes)
                    {
                        rScript.Replace(node, new IdentifierExpression("replacement"));
                    }
                });
            }

            Assert.AreEqual(@"class Test1
{
	public int replacement;
}", context.GetSideDocumentText(0));

            Assert.AreEqual(@"class Test2
{
	public void Foo(Test1 test1)
	{
		replacement = 1;
		replacement = 2;
	}
}", context.GetSideDocumentText(1));
        }
        // TODO: Remove this when the formatter handles object and collection initializers
        // This tests the expected code vs the actual code based on their ASTs instead of the text they produce.
        public new void Test <T>(string input, string output, int action = 0, bool expectErrors = false)
            where T : CodeActionProvider, new ()
        {
            string result = RunContextAction(new T(), HomogenizeEol(input), action, expectErrors);

            var expectedContext = TestRefactoringContext.Create(output, expectErrors);
            var actualContext   = TestRefactoringContext.Create(result, expectErrors);

            bool passed = expectedContext.RootNode.IsMatch(actualContext.RootNode);

            if (!passed)
            {
                Console.WriteLine("-----------Expected:");
                Console.WriteLine(output);
                Console.WriteLine("-----------Got:");
                Console.WriteLine(result);
            }
            Assert.IsTrue(passed, "The generated code and the expected code was not syntactically identical. See output for details.");
        }
            void DoLocalOperationOn(TestRefactoringContext localContext, IEnumerable <IEntity> entities, Action <RefactoringContext, Script, IEnumerable <AstNode> > callback)
            {
                List <AstNode> nodes     = new List <AstNode>();
                FindReferences refFinder = new FindReferences();

                refFinder.FindCallsThroughInterface = true;
                refFinder.FindReferencesInFile(refFinder.GetSearchScopes(entities),
                                               localContext.UnresolvedFile,
                                               localContext.RootNode as SyntaxTree,
                                               localContext.Compilation,
                                               (node, result) => {
                    nodes.Add(node);
                },
                                               CancellationToken.None);

                using (var script = localContext.StartScript()) {
                    callback(localContext, script, nodes);
                }
            }
Exemple #15
0
        public void TestRename()
        {
            List <string> contents = new List <string>()
            {
                @"class Test1
{
	public int $x;
}", @"class Test2
{
	public void Foo(Test1 test1)
	{
		test1.x = 1;
		test1.x = 2;
	}
}"
            };
            var context = TestRefactoringContext.Create(contents, 0);

            using (var script = context.StartScript()) {
                var variable = context.GetNode <VariableInitializer>();
                script.Rename(((MemberResolveResult)context.Resolve(variable)).Member, "newName");
            }

            Assert.AreEqual(@"class Test1
{
	public int newName;
}", context.GetSideDocumentText(0));

            Assert.AreEqual(@"class Test2
{
	public void Foo(Test1 test1)
	{
		test1.newName = 1;
		test1.newName = 2;
	}
}", context.GetSideDocumentText(1));
        }
 public TestScript(TestRefactoringContext context) : base(context.doc, context.FormattingOptions, new TextEditorOptions())
 {
     this.context = context;
 }
        public static TestRefactoringContext Create(List <string> contents, int mainIndex, bool expectErrors = false)
        {
            List <int>                  indexes         = new List <int>();
            List <int>                  selectionStarts = new List <int>();
            List <int>                  selectionEnds   = new List <int>();
            List <IDocument>            documents       = new List <IDocument>();
            List <CSharpUnresolvedFile> unresolvedFiles = new List <CSharpUnresolvedFile>();
            List <SyntaxTree>           units           = new List <SyntaxTree>();

            for (int i = 0; i < contents.Count; i++)
            {
                string content = contents[i];
                int    idx     = content.IndexOf("$");
                if (idx >= 0)
                {
                    content = content.Substring(0, idx) + content.Substring(idx + 1);
                }
                int idx1           = content.IndexOf("<-");
                int idx2           = content.IndexOf("->");
                int selectionStart = 0;
                int selectionEnd   = 0;
                if (0 <= idx1 && idx1 < idx2)
                {
                    content        = content.Substring(0, idx2) + content.Substring(idx2 + 2);
                    content        = content.Substring(0, idx1) + content.Substring(idx1 + 2);
                    selectionStart = idx1;
                    selectionEnd   = idx2 - 2;
                    idx            = selectionEnd;
                }
                indexes.Add(idx);
                selectionStarts.Add(selectionStart);
                selectionEnds.Add(selectionEnd);
                var doc    = new StringBuilderDocument(content);
                var parser = new CSharpParser();
                var unit   = parser.Parse(content, "program_" + i + ".cs");
                if (!expectErrors)
                {
                    if (parser.HasErrors)
                    {
                        Console.WriteLine(content);
                        Console.WriteLine("----");
                    }
                    foreach (var error in parser.Errors)
                    {
                        Console.WriteLine(error.Message);
                    }
                    Assert.IsFalse(parser.HasErrors, "The file " + i + " contains unexpected parsing errors.");
                }
                else
                {
                    Assert.IsTrue(parser.HasErrors, "Expected parsing errors, but the file " + i + "doesn't contain any.");
                }
                unit.Freeze();
                CSharpUnresolvedFile unresolvedFile = unit.ToTypeSystem();
                units.Add(unit);
                documents.Add(doc);
                unresolvedFiles.Add(unresolvedFile);
            }

            IProjectContent pc = new CSharpProjectContent();

            pc = pc.AddOrUpdateFiles(unresolvedFiles);
            pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });

            var compilation = pc.CreateCompilation();
            List <TestRefactoringContext> contexts = new List <TestRefactoringContext>();

            for (int documentIndex = 0; documentIndex < documents.Count; ++documentIndex)
            {
                var          doc      = documents [documentIndex];
                var          resolver = new CSharpAstResolver(compilation, units[documentIndex], unresolvedFiles[documentIndex]);
                TextLocation location = TextLocation.Empty;
                if (indexes[documentIndex] >= 0)
                {
                    location = doc.GetLocation(indexes[documentIndex]);
                }
                var context = new TestRefactoringContext(doc, location, resolver)
                {
                    selectionStart  = selectionStarts[documentIndex],
                    selectionEnd    = selectionEnds[documentIndex],
                    projectContexts = contexts
                };

                contexts.Add(context);
            }

            return(contexts [mainIndex]);
        }
			public TestScript(TestRefactoringContext context) : base(context.doc, FormattingOptionsFactory.CreateMono (), new TextEditorOptions ())
			{
				this.context = context;
			}
		public static TestRefactoringContext Create (List<string> contents, int mainIndex, bool expectErrors = false, CSharpParser parser = null)
		{
			List<int> indexes = new List<int>();
			List<int> selectionStarts = new List<int>();
			List<int> selectionEnds = new List<int>();
			List<IDocument> documents = new List<IDocument>();
			List<CSharpUnresolvedFile> unresolvedFiles = new List<CSharpUnresolvedFile>();
			List<SyntaxTree> units = new List<SyntaxTree>();

			for (int i = 0; i < contents.Count; i++) {
				string content = contents[i];
				int idx = content.IndexOf("$");
				if (idx >= 0)
					content = content.Substring(0, idx) + content.Substring(idx + 1);
				int idx1 = content.IndexOf("<-");
				int idx2 = content.IndexOf("->");
				int selectionStart = 0;
				int selectionEnd = 0;
				if (0 <= idx1 && idx1 < idx2) {
					content = content.Substring(0, idx2) + content.Substring(idx2 + 2);
					content = content.Substring(0, idx1) + content.Substring(idx1 + 2);
					selectionStart = idx1;
					selectionEnd = idx2 - 2;
					idx = selectionEnd;
				}
				indexes.Add(idx);
				selectionStarts.Add(selectionStart);
				selectionEnds.Add(selectionEnd);
				var doc = new StringBuilderDocument(content);
				if (parser == null)
					parser = new CSharpParser();
				var unit = parser.Parse(content, "program_" + i + ".cs");
				if (!expectErrors) {
					if (parser.HasErrors) {
						Console.WriteLine(content);
						Console.WriteLine("----");
					}
					foreach (var error in parser.ErrorsAndWarnings) {
						Console.WriteLine(error.Message);
					}
					Assert.IsFalse(parser.HasErrors, "The file " + i + " contains unexpected parsing errors.");
				}
				else {
					Assert.IsTrue(parser.HasErrors, "Expected parsing errors, but the file " + i + "doesn't contain any.");
				}
				unit.Freeze();
				CSharpUnresolvedFile unresolvedFile = unit.ToTypeSystem();
				units.Add(unit);
				documents.Add(doc);
				unresolvedFiles.Add(unresolvedFile);
			}

			IProjectContent pc = new CSharpProjectContent ();
			pc = pc.AddOrUpdateFiles (unresolvedFiles);
			pc = pc.AddAssemblyReferences (new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });

			var compilation = pc.CreateCompilation ();
			List<TestRefactoringContext> contexts = new List<TestRefactoringContext>();

			for (int documentIndex = 0; documentIndex < documents.Count; ++documentIndex)
			{
				var doc = documents [documentIndex];
				var resolver = new CSharpAstResolver (compilation, units[documentIndex], unresolvedFiles[documentIndex]);
				TextLocation location = TextLocation.Empty;
				if (indexes[documentIndex] >= 0)
					location = doc.GetLocation (indexes[documentIndex]);
				var context = new TestRefactoringContext(doc, location, resolver) {
					selectionStart = selectionStarts[documentIndex],
					selectionEnd = selectionEnds[documentIndex],
					projectContexts = contexts,
					version = parser.CompilerSettings.LanguageVersion,
					defaultNamespace = "Test"
				};

				contexts.Add(context);
			}

			return contexts [mainIndex];
		}
		protected static void CheckFix (TestRefactoringContext ctx, CodeIssue issue, string expectedOutput)
		{
			using (var script = ctx.StartScript ())
				issue.Actions.First ().Run (script);
			Assert.AreEqual (expectedOutput, ctx.Text);
		}
		protected static List<CodeIssue> GetIssues (ICodeIssueProvider action, string input, out TestRefactoringContext context)
		{
			context = TestRefactoringContext.Create (input);
			
			return new List<CodeIssue> (action.GetIssues (context));
		}
 public TestScript(TestRefactoringContext context) : base(context.doc, FormattingOptionsFactory.CreateMono(), new TextEditorOptions())
 {
     this.context = context;
 }
 public TestScript(TestRefactoringContext context)
     : base(context.doc, context.FormattingOptions, new TextEditorOptions ())
 {
     this.context = context;
 }
			void DoLocalOperationOn(TestRefactoringContext localContext, IEnumerable<IEntity> entities, Action<RefactoringContext, Script, IEnumerable<AstNode>> callback)
			{
				List<AstNode> nodes = new List<AstNode>();
				FindReferences refFinder = new FindReferences();
				refFinder.FindCallsThroughInterface = true;
				refFinder.FindReferencesInFile(refFinder.GetSearchScopes(entities),
				                               localContext.UnresolvedFile,
				                               localContext.RootNode as SyntaxTree,
				                               localContext.Compilation,
				                               (node, result) => {
					                               nodes.Add(node);
				                               },
				                               CancellationToken.None);

				using (var script = localContext.StartScript()) {
					callback(localContext, script, nodes);
				}
			}