public void ProjectFileTypeIsRegistered()
        {
            Assert.NotNull(T4ProjectFileType.Instance);
            var projectFileTypes = ShellInstance.GetComponent <IProjectFileTypes>();

            Assert.NotNull(projectFileTypes.GetFileType(T4ProjectFileType.Name));
        }
Exemple #2
0
        public override void TestFixtureTearDown()
        {
            /* this logic is needed to undo the Resharper solution caching in place for tests
             * that break the more complex 'solution based tests' within the test solution */
            base.TestFixtureTearDown();

            RunGuarded(
                () => ShellInstance.GetComponent <TestSolutionManager>().CloseSolution());
        }
        public override void TestFixtureTearDown()
        {
            Assert.IsNotNull(_loadedTestSolution, "_loadedTestSolution == null");
            RunGuarded(() =>
            {
                ShellInstance.GetComponent <TestSolutionManager>().CloseSolution(_loadedTestSolution);
                _loadedTestSolution = null;
            });

            base.TestFixtureTearDown();
        }
        private string GetDll(string filename)
        {
            var source = GetTestDataFilePath2(filename);
            var dll    = source.ChangeExtension("dll");

            if (!dll.ExistsFile || source.FileModificationTimeUtc > dll.FileModificationTimeUtc)
            {
                var references = GetReferencedAssemblies(GetPlatformID()).ToArray();
                var frameworkDetectionHelper = ShellInstance.GetComponent <IFrameworkDetectionHelper>();
                CompileCs.Compile(frameworkDetectionHelper, source, dll, references, GetPlatformID().Version);
            }

            return(dll.Name);
        }
        protected override void DoTest(IProject testProject)
        {
            Lifetimes.Using(lifetime =>
            {
                ChangeSettingsTemporarily(lifetime);

                var settingsStore = ShellInstance.GetComponent <SettingsStore>();
                var context       = ContextRange.ManuallyRestrictWritesToOneContext((_, contexts) => contexts.Empty);
                var settings      = settingsStore.BindToContextTransient(context);

                settings.SetValue((PostfixTemplatesSettings s) => s.UseBracesForEmbeddedStatements, false);

                base.DoTest(testProject);
            });
        }
Exemple #6
0
        protected override void DoTest(IProject testProject)
        {
            ShellInstance.GetComponent <TestIdGenerator>().Reset();
            using (var textControl = OpenTextControl(testProject))
            {
                ExecuteWithGold(textControl.Document, sw =>
                {
                    var files = textControl
                                .Document
                                .GetPsiSourceFiles(Solution)
                                .SelectMany(s => s.GetPsiFiles <TLanguage>())
                                .ToList();
                    files.Sort((file1, file2) => String.Compare(file1.Language.Name, file2.Language.Name, StringComparison.Ordinal));
                    foreach (var psiFile in files)
                    {
                        // Assert all chameleons are closed by default
                        var chameleons = psiFile.ThisAndDescendants <IChameleonNode>();
                        while (chameleons.MoveNext())
                        {
                            var chameleonNode = chameleons.Current;
                            if (chameleonNode.IsOpened && !(chameleonNode is IComment))
                            {
                                Assertion.Fail("Found chameleon node that was opened after parser is invoked: '{0}'", chameleonNode.GetText());
                            }

                            chameleons.SkipThisNode();
                        }

                        // Dump the PSI tree, opening all chameleons
                        sw.WriteLine("Language: {0}", psiFile.Language);
                        DebugUtil.DumpPsi(sw, psiFile);
                        sw.WriteLine();
                        if (((IFileImpl)psiFile).SecondaryRangeTranslator is RangeTranslatorWithGeneratedRangeMap rangeTranslator)
                        {
                            WriteCommentedText(sw, "//", rangeTranslator.Dump(psiFile));
                        }

                        // Verify textual contents
                        var originalText = textControl.Document.GetText();
                        Assert.AreEqual(originalText, psiFile.GetText(), "Reconstructed text mismatch");
                        CheckRange(originalText, psiFile);
                    }
                });
            }
        }
Exemple #7
0
        protected void RunTest(string testName, Action <IEnumerable <RegistrationInfo> > action)
        {
            string fileName = testName + Extension;
            var    dataPath = new DirectoryInfo(Path.Combine(SolutionItemsBasePath, RelativeTypesPath));
            var    fileSet  = dataPath.GetFiles("*.cs").SelectNotNull(fileInfo => Path.Combine(RelativeTypesPath, fileInfo.Name)).Concat(new[] { fileName });

            WithSingleProject(fileSet, (lifetime, project) => RunGuarded(() =>
            {
                var searchDomainFactory = ShellInstance.GetComponent <SearchDomainFactory>();
                var patternSearcher     = new PatternSearcher(searchDomainFactory);
                var solutionnAnalyzer   = new SolutionAnalyzer(patternSearcher);
                solutionnAnalyzer.AddContainer(ContainerInfo);

                var componentRegistrations = solutionnAnalyzer.Analyze();

                action(componentRegistrations);
            }));
        }
        protected override void DoTest(Lifetime lifetime, IProject testProject)
        {
            var projectFile = testProject.GetSubItems(myTestName).Single() as IProjectFile;

            Assert.IsNotNull(projectFile, "projectFile != null");

            var sourceFile = projectFile.ToSourceFile();

            Assert.IsNotNull(sourceFile, "sourceFile != null");

            var builder = ShellInstance
                          .GetComponent <IProjectFileTypeServices>()
                          .GetService <IProjectFileCodeStructureProvider>(T4ProjectFileType.Instance);
            var rootElement = builder.Build(sourceFile, new CodeStructureOptions {
                BuildInheritanceInformation = true
            });

            ExecuteWithGold(projectFile, sb => rootElement.Dump(sb));
        }
        private string EnsureTestDll(string testName)
        {
            // Get dll + cs file (use TestFileExtensionAttribute to use other
            // than .cs). Check existence + file stamps. If missing or out of
            // date, rebuild. Then call DoTestSolution with dll
            var source = GetTestDataFilePath2(testName + Extension);

            testName = testName.EndsWith(XunitEnvironment.Id) ? testName : testName + "." + XunitEnvironment.Id;
            var dll = GetTestDataFilePath2(testName + ".dll");

            var references = GetReferencedAssemblies(GetPlatformID()).Select(System.Environment.ExpandEnvironmentVariables).ToArray();

            if (!dll.ExistsFile || source.FileModificationTimeUtc > dll.FileModificationTimeUtc || ReferencesAreNewer(references, dll.FileModificationTimeUtc))
            {
                var frameworkDetectionHelper = ShellInstance.GetComponent <IFrameworkDetectionHelper>();
                CompileCs.Compile(frameworkDetectionHelper, source, dll, references, GetPlatformID().Version);
            }
            return(dll.Name);
        }
        protected override void DoTest(IProject testProject)
        {
            var definition = Lifetimes.Define(EternalLifetime.Instance);

            try
            {
                ChangeSettingsTemporarily(definition.Lifetime);

#if RESHARPER8
                var settingsStore = ShellInstance.GetComponent <SettingsStore>();
                var store         = settingsStore.BindToContext(settingsStore.DataContexts.Empty);

                store.SetValue((IntroduceVariableUseVarSettings s) => s.UseVarForIntroduceVariableRefactoringEvident, true);
                store.SetValue((IntroduceVariableUseVarSettings s) => s.UseVarForIntroduceVariableRefactoring, true);
#endif

                base.DoTest(testProject);
            }
            finally
            {
                definition.Terminate();
            }
        }
Exemple #11
0
        protected override void DoTest(IProject testProject)
        {
            var positionsToCheck = GetCaretPositions().DefaultIfEmpty(GetCaretPosition()).ToList();

            Assert.IsNotEmpty(positionsToCheck, "Nothing to check - put {caret} where necessary");

            var reparsedNodes = new List <ITreeNode>();

            ShellInstance.GetComponent <TestIdGenerator>().Reset();
            var psiFiles = Solution.GetPsiServices().Files;

            void PsiChanged(ITreeNode node, PsiChangedElementType type)
            {
                if (node != null)
                {
                    reparsedNodes.Add(node);
                }
            }

            psiFiles.AfterPsiChanged += PsiChanged;

            try
            {
                var textControl = OpenTextControl();
                {
                    using (CompilationContextCookie.GetOrCreate(testProject.GetResolveContext()))
                    {
                        // number of original files
                        var originalFiles = new Dictionary <IPsiSourceFile, int>();
                        foreach (var caretPosition in positionsToCheck)
                        {
                            var projectFile = GetProjectFile(testProject, caretPosition.FileName);
                            Assert.NotNull(projectFile);

                            foreach (var psiSourceFile in projectFile.ToSourceFiles())
                            {
                                originalFiles.Add(psiSourceFile, GetPsiFiles(psiSourceFile).Count);
                            }
                        }

                        var checkAll = GetSetting(textControl.Document.Buffer, "CHECKALL");

                        // change text
                        var actions = GetSettings(textControl.Document.Buffer, "ACTION");
                        if (actions.Count == 0)
                        {
                            throw new Exception("No actions found");
                        }
                        foreach (var action in actions)
                        {
                            if (action.Length == 0)
                            {
                                continue;
                            }
                            var text = action.Substring(1).Replace("{LEFT}", "{").Replace("{RIGHT}", "}");
                            switch (action.ToCharArray()[0])
                            {
                            case '+':
                                textControl.Document.InsertText(textControl.Caret.Offset(), text);
                                break;

                            case '-':
                                textControl.Document.DeleteText(TextRange.FromLength(textControl.Caret.Offset(), Convert.ToInt32(text)));
                                break;

                            case '>':
                                textControl.Caret.MoveTo(textControl.Caret.Offset() + Convert.ToInt32(text),
                                                         CaretVisualPlacement.Generic);
                                break;

                            case '<':
                                textControl.Caret.MoveTo(textControl.Caret.Offset() - Convert.ToInt32(text),
                                                         CaretVisualPlacement.Generic);
                                break;

                            default:
                                var actionManager = ShellInstance.GetComponent <IActionManager>();
                                actionManager.Defs.GetActionDefById(TextControlActions.Composition.Compose(action, false))
                                .EvaluateAndExecute(actionManager);
                                break;
                            }

                            if (String.Equals(checkAll, "true", StringComparison.InvariantCultureIgnoreCase))
                            {
                                foreach (var data in originalFiles)
                                {
                                    GetPsiFiles(data.Key);
                                }
                            }
                        }

                        foreach (var data in originalFiles)
                        {
                            var psiSourceFile = data.Key;

                            Assert.IsTrue(psiSourceFile.IsValid());

                            // get reparsed files
                            var reparsedFiles = GetPsiFiles(psiSourceFile);

                            Assert.AreEqual(reparsedFiles.Count, data.Value, "Reparsed psi files count mismatch for {0}", psiSourceFile);

                            // check reparsed element
                            ExecuteWithGold(psiSourceFile, writer =>
                            {
                                if (reparsedNodes.IsEmpty())
                                {
                                    writer.Write("Fully reparsed");
                                }
                                else
                                {
                                    reparsedNodes.Sort((n1, n2) => String.CompareOrdinal(n1.Language.Name, n2.Language.Name));
                                    foreach (var reparsedNode in reparsedNodes)
                                    {
                                        if (reparsedNode is IFile)
                                        {
                                            writer.WriteLine("{0}: Fully reparsed", reparsedNode.Language);
                                        }
                                        else
                                        {
                                            var nodeType = reparsedNode.GetType();
                                            writer.WriteLine("{0}: reparsed node type: {1}, text: {2}", reparsedNode.Language,
                                                             PresentNodeType(nodeType), reparsedNode.GetText());
                                        }
                                    }
                                }
                                if (DoDumpRanges)
                                {
                                    DumpRanges <PsiLanguageType>(psiSourceFile, writer);
                                }
                            });

                            // drop psi files cache
                            WriteLockCookie.Execute(() => psiFiles.MarkAsDirty(psiSourceFile));

                            var files = GetPsiFiles(psiSourceFile);
                            Assert.AreEqual(files.Count, reparsedFiles.Count, "Psi files count mismatch");

                            foreach (var pair in files)
                            {
                                var language = pair.Key;
                                Assert.IsTrue(reparsedFiles.TryGetValue(language, out var reparsedFile), "Failed to find psi file for {0}", language);

                                CompareTrees(pair.Value, reparsedFile);
                            }
                        }
                    }
                }
            }
            finally
            {
                psiFiles.AfterPsiChanged -= PsiChanged;
                reparsedNodes.Clear();
            }
        }
        public void ProjectFileTypeFromExtension()
        {
            var projectFileExtensions = ShellInstance.GetComponent <IProjectFileExtensions>();

            Assert.AreSame(T4ProjectFileType.Instance, projectFileExtensions.GetFileType(T4FileExtensions.MainExtension));
        }
Exemple #13
0
        protected override void ProcessAction(Lifetime lifetime, Func <ITextControl, TAction> actionCreator, IProject project)
        {
            var solution        = project.GetSolution();
            var documentManager = solution.GetComponent <DocumentManager>();
            var caretPosition   = GetCaretPosition() ?? CaretPositionsProcessor.PositionNames.SelectMany(_ => CaretPositionsProcessor.Positions(_) as IEnumerable <CaretPosition>).First("Caret position is not set. Please add {caret} or {selstart} to a test file.");
            var textControl     = OpenTextControl(lifetime, project, caretPosition);
            var name            = InitTextControl(textControl);
            var contextAction   = actionCreator(textControl);

            ExecuteWithGold(textControl.Document, sw =>
            {
                Assert.NotNull(contextAction);
                var list = ComputeActions(contextAction, textControl).Select(x => x.BulbAction).ToList();
                if (list.Count == 0)
                {
                    OnNoItemsForAvailableAction(contextAction, textControl, sw);
                }
                else
                {
                    var bulbAction1 = SelectItem(contextAction, name, textControl);
                    if (bulbAction1 == null)
                    {
                        sw.WriteLine("NOT AVAILABLE FOR {0}", name);
                        foreach (var bulbAction2 in list)
                        {
                            sw.WriteLine(bulbAction2.Text);
                        }
                    }
                    else
                    {
                        var document = textControl.Document;
                        ExecuteItem(textControl, bulbAction1, solution);
                        var currentSession = ShellInstance.GetComponent <HotspotSessionExecutor>().CurrentSession;
                        if (currentSession != null)
                        {
                            while (!currentSession.HotspotSession.IsFinished)
                            {
                                ProcessHotspot(textControl, currentSession.HotspotSession.CurrentHotspot.NotNull());
                                currentSession.HotspotSession.GoToNextHotspotSync();
                            }
                        }
                        var projectFile = documentManager.TryGetProjectFile(document);
                        if (projectFile == null)
                        {
                            sw.Write("File is removed");
                        }
                        else
                        {
                            DumpTextControl(textControl, DumpCaretPosition, DumpSelection)(sw);
                            WriteCodeBehind(document, sw);
                            if (LanguageForDumpRanges == null)
                            {
                                return;
                            }
                            DumpRanges(projectFile.ToSourceFile().NotNull(), sw, false, LanguageForDumpRanges.GetType());
                        }
                    }
                }
            });

            foreach (var allProjectFile in project.GetAllProjectFiles())
            {
                var projectFile = allProjectFile;
                if (!(projectFile.Location == caretPosition.FileName) && !Enumerable.Contains(CaretPositionsProcessor.SkipExtensions, projectFile.Location.ExtensionWithDot, StringComparer.OrdinalIgnoreCase))
                {
                    ExecuteWithGold(projectFile, sw =>
                    {
                        var document = documentManager.GetOrCreateDocument(projectFile);
                        sw.Write(document.GetText());
                        if (LanguageForDumpRanges == null)
                        {
                            return;
                        }
                        DumpRanges(projectFile.ToSourceFile().NotNull(), sw, false, LanguageForDumpRanges.GetType());
                    });
                }
            }
        }
Exemple #14
0
 public void TestThatSomePlatformShellComponentIsAccessible() =>
 Assert.NotNull(ShellInstance.GetComponent <ITaskBarManager>());