public void SharedEngineVariables() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create an engine provider with an empty service provider. IPythonEngineProvider engineProvider = CreateEngineProvider(provider); // Get the shared engine. IEngine engine = engineProvider.GetSharedEngine(); // The "engine" variable should always be defined. object engObj = engine.Evaluate("engine"); Assert.IsNotNull(engObj); // The "dte" variable should be set to null. object dte = engine.Evaluate("dte"); Assert.IsNull(dte); // Now add the EnvDTE.DTE service to the service provider. BaseMock dteMock = MockFactories.DTEFactory.GetInstance(); provider.AddService(typeof(EnvDTE.DTE), dteMock, false); // Create a new engine provider. engineProvider = CreateEngineProvider(provider); // Get the shared engine. engine = engineProvider.GetSharedEngine(); // The "engine" variable should always be defined. engObj = engine.Evaluate("engine"); Assert.IsNotNull(engObj); // Now the "dte" variable should be set. dte = engine.Evaluate("dte"); Assert.IsNotNull(dte); } }
public void ValidateToolWindowShown() { IVsPackage package = new CloudFoundryVisualStudioPackage() as IVsPackage; // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); //Add uishell service that knows how to create a toolwindow BaseMock uiShellService = UIShellServiceMock.GetUiShellInstanceCreateToolWin(); serviceProvider.AddService(typeof(SVsUIShell), uiShellService, false); // Add site support for activity log BaseMock activityLogMock = new GenericMockFactory("MockVsActivityLog", new[] { typeof(Microsoft.VisualStudio.Shell.Interop.IVsActivityLog) }).GetInstance(); serviceProvider.AddService(typeof(Microsoft.VisualStudio.Shell.Interop.SVsActivityLog), activityLogMock, true); // Add site support to register editor factory BaseMock registerEditor = RegisterEditorMock.GetRegisterEditorsInstance(); serviceProvider.AddService(typeof(SVsRegisterEditors), registerEditor, false); // Site the package Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK"); MethodInfo method = typeof(CloudFoundryVisualStudioPackage).GetMethod("ShowToolWindow", BindingFlags.NonPublic | BindingFlags.Instance); object result = method.Invoke(package, new object[] { null, null }); }
public void CreateEditorInstanceTest() { //Create the editor factory EditorFactory targetFactory = editorFactory; // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); AddBasicSiteSupport(serviceProvider); // Site the editor factory Assert.AreEqual(0, targetFactory.SetSite(serviceProvider), "SetSite did not return S_OK"); IntPtr ppunkDocView; IntPtr ppunkDocData; string pbstrEditorCaption = String.Empty; Guid pguidCmdUI = Guid.Empty; int pgrfCDW = 0; uint cef_option = VSConstants.CEF_OPENFILE; int actual_result = targetFactory.CreateEditorInstance(cef_option, null, null, null, 0, IntPtr.Zero, out ppunkDocView, out ppunkDocData, out pbstrEditorCaption, out pguidCmdUI, out pgrfCDW); Assert.AreEqual(VSConstants.S_OK, actual_result); }
public void OneTriggerNoText() { using (OleServiceProvider provider = new OleServiceProvider()) { ResetScopeState(); // Create a mock engine provider. BaseMock mockEngineProvider = MockFactories.EngineProviderFactory.GetInstance(); // Create a mock engine. BaseMock mockEngine = MockFactories.EngineFactory.GetInstance(); // Set this engine as the one returned from the GetSharedEngine of the engine provider. mockEngineProvider.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IPythonEngineProvider), "GetSharedEngine"), new object[] { (IEngine)mockEngine }); // Add the engine provider to the list of the services. provider.AddService(typeof(IPythonEngineProvider), mockEngineProvider, false); // Create the scanner for this test. BaseMock scannerMock = MockFactories.ScannerFactory.GetInstance(); scannerMock["Iteration"] = 0; TokenInfo token = new TokenInfo(); token.StartIndex = 0; token.EndIndex = 1; token.Trigger = TokenTriggers.MemberSelect; scannerMock["Tokens"] = new TokenInfo[] { token }; scannerMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IScanner).FullName, "ScanTokenAndProvideInfoAboutIt"), new EventHandler <CallbackArgs>(StandardScannerCallback)); Declarations declarations = ExecuteGetDeclarations(".", scannerMock as IScanner, provider); Assert.IsTrue(0 == mockEngine.TotalCallsAllFunctions()); } }
public void InitializeMenuCommand() { // Create the package IVsPackage package = new VSThrowawayPackagePackage() as IVsPackage; Assert.IsNotNull(package, "The object does not implement IVsPackage"); // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); // Add site support to register editor factory BaseMock registerEditor = VSThrowawayPackage_UnitTests.EditorTests.RegisterEditorsServiceMock.GetRegisterEditorsInstance(); serviceProvider.AddService(typeof(SVsRegisterEditors), registerEditor, false); // Site the package Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK"); //Verify that the menu command can be found CommandID menuCommandID = new CommandID(VSJamSession.VSThrowawayPackage.GuidList.guidVSThrowawayPackageCmdSet, (int)VSJamSession.VSThrowawayPackage.PkgCmdIDList.startJamSession); System.Reflection.MethodInfo info = typeof(Package).GetMethod("GetService", BindingFlags.Instance | BindingFlags.NonPublic); Assert.IsNotNull(info); OleMenuCommandService mcs = info.Invoke(package, new object[] { (typeof(IMenuCommandService)) }) as OleMenuCommandService; Assert.IsNotNull(mcs.FindCommand(menuCommandID)); }
/// <summary> /// Retrieves the <see cref="IServiceLocator"/> for the given project. /// </summary> /// <exception cref="ArgumentNullException">The <paramref name="project"/> parameter was null.</exception> /// <exception cref="InvalidOperationException">The required <see cref="IComponentModel"/> service was not found.</exception> public static IServiceLocator GetServiceLocator(this IVsProject project) { Guard.NotNull(nameof(project), project); IServiceProvider serviceProvider; Ole.IServiceProvider site; if (ErrorHandler.Failed(((IVsHierarchy)project).GetSite(out site)) || site == null) { serviceProvider = Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider; } else { serviceProvider = new OleServiceProvider(site); } var components = serviceProvider.GetService <SComponentModel, IComponentModel>(); try { return(components.GetService <IServiceLocatorProvider>().GetServiceLocator(project)); } catch (ImportCardinalityMismatchException ex) { throw new MissingDependencyException(Strings.ServiceLocator.MissingDependency(typeof(IServiceLocatorProvider)), ex); } }
public void EngineInitialization() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.CreateBufferWithMarker(); LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create a mock engine provider. BaseMock mockEngineProvider = MockFactories.EngineProviderFactory.GetInstance(); // Create a mock engine. BaseMock mockEngine = MockFactories.CreateStandardEngine(); // Set this engine as the one returned from the GetSharedEngine of the engine provider. mockEngineProvider.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IPythonEngineProvider), "GetSharedEngine"), new object[] { (IEngine)mockEngine }); // Add the engine provider to the list of the services. provider.AddService(typeof(IPythonEngineProvider), mockEngineProvider, false); // Create the console window using (IDisposable disposableObject = CommandWindowHelper.CreateConsoleWindow(provider) as IDisposable) { IVsWindowPane windowPane = disposableObject as IVsWindowPane; Assert.IsNotNull(windowPane); // Verify that the shared engine was get. Assert.IsTrue(1 == mockEngineProvider.FunctionCalls(string.Format("{0}.{1}", typeof(IPythonEngineProvider), "GetSharedEngine"))); Assert.IsTrue(1 == mockEngine.FunctionCalls(string.Format("{0}.{1}", typeof(IEngine), "set_StdErr"))); Assert.IsTrue(1 == mockEngine.FunctionCalls(string.Format("{0}.{1}", typeof(IEngine), "set_StdOut"))); } } }
public void PackageCreation() { // Create a service provider with basic services to site the package. using (OleServiceProvider provider = OleServiceProvider.CreateOleServiceProviderWithBasicServices()) { IVsPackage package = null; try { // Create the package and verify that implements IVsPackage. package = new PythonConsolePackage() as IVsPackage; Assert.IsNotNull(package); // Verify that SetSite succeeded. int hr = package.SetSite(provider); Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded(hr)); } finally { if (null != package) { package.SetSite(null); package.Close(); } } } }
public void ShowToolwindowNegativeTest() { IVsPackage package = new GitWorkItemsPackage() as IVsPackage; // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); //Add uishell service that knows how to create a toolwindow BaseMock uiShellService = UIShellServiceMock.GetUiShellInstanceCreateToolWinReturnsNull(); serviceProvider.AddService(typeof(SVsUIShell), uiShellService, false); // Site the package Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK"); MethodInfo method = typeof(GitWorkItemsPackage).GetMethod("ShowToolWindow", BindingFlags.NonPublic | BindingFlags.Instance); //Invoke thows TargetInvocationException, but we want it's inner Exception thrown by ShowToolWindow, InvalidOperationException. try { object result = method.Invoke(package, new object[] { null, null }); } catch (Exception e) { throw e.InnerException; } }
public void TestOutputNoPane() { // Create an instance of the package and initialize it so that the GetService // will succeed, but the GetPane will fail. // As first create a service provider. using (OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices()) { // Now create the mock object for the output window. if (null == mockOutputWindowFactory) { mockOutputWindowFactory = new GenericMockFactory("MockOutputWindow", new Type[] { typeof(IVsOutputWindow) }); } BaseMock mockBase = mockOutputWindowFactory.GetInstance() as BaseMock; mockBase.AddMethodReturnValues(string.Format("{0}.{1}", typeof(IVsOutputWindow).FullName, "GetPane"), new object[] { -1, Guid.Empty, null }); // Add the output window to the services provided by the service provider. serviceProvider.AddService(typeof(SVsOutputWindow), mockBase, false); // Create an instance of the package and initialize it calling SetSite. ServicesPackage package = new ServicesPackage(); int result = ((IVsPackage)package).SetSite(serviceProvider); Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded(result), "SetSite failed."); // Now we can create an instance of the service MyGlobalService service = new MyGlobalService(package); service.GlobalServiceFunction(); ((IVsPackage)package).SetSite(null); ((IVsPackage)package).Close(); } }
public void MenuItemCallback() { // Create the package IVsPackage package = new VsOnBuildExtensionPackage() as IVsPackage; Assert.IsNotNull(package, "The object does not implement IVsPackage"); // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); // Create a UIShell service mock and proffer the service so that it can called from the MenuItemCallback method BaseMock uishellMock = UIShellServiceMock.GetUiShellInstance(); serviceProvider.AddService(typeof(SVsUIShell), uishellMock, true); // Site the package Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK"); //Invoke private method on package class and observe that the method does not throw System.Reflection.MethodInfo info = package.GetType().GetMethod("MenuItemCallback", BindingFlags.Instance | BindingFlags.NonPublic); Assert.IsNotNull(info, "Failed to get the private method MenuItemCallback throug refplection"); info.Invoke(package, new object[] { null, null }); //Clean up services serviceProvider.RemoveService(typeof(SVsUIShell)); }
/// <summary> /// Add some basic service mock objects to the service provider. /// </summary> /// <param name="serviceProvider"></param> public static void AddBasicSiteSupport(OleServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } // Add site support for UI Shell BaseMock uiShell = MockServicesProvider.GetUiShellInstance0(); serviceProvider.AddService(typeof(SVsUIShell), uiShell, false); serviceProvider.AddService(typeof(SVsUIShellOpenDocument), (IVsUIShellOpenDocument)uiShell, false); //Add site support for Running Document Table BaseMock runningDoc = MockServicesProvider.GetRunningDocTableInstance(); serviceProvider.AddService(typeof(SVsRunningDocumentTable), runningDoc, false); //Add site support for IVsTextManager BaseMock queryEditQuerySave = MockServicesProvider.GetQueryEditQuerySaveInstance(); serviceProvider.AddService(typeof(SVsQueryEditQuerySave), queryEditQuerySave, false); BaseMock toolbox = MockIVsToolbox.GetIVsToolboxInstance(); serviceProvider.AddService(typeof(SVsToolbox), toolbox, false); }
private static void CreateToolWindowCallBack(object caller, CallbackArgs arguments) { arguments.ReturnValue = VSConstants.S_OK; // Create the output mock object for the frame IVsWindowFrame frame = MockWindowFrameProvider.GetBaseFrame(); arguments.SetParameter(9, frame); // The window pane (if one is provided) needs to be sited IVsWindowPane pane = arguments.GetParameter(2) as IVsWindowPane; if (pane != null) { // Create a service provider to site the window pane OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); // It needs to provide STrackSelection GenericMockFactory trackSelectionFactory = MockWindowFrameProvider.TrackSelectionFactory; serviceProvider.AddService(typeof(STrackSelection), trackSelectionFactory.GetInstance(), false); // Add support for output window serviceProvider.AddService(typeof(SVsOutputWindow), new OutputWindowService(), false); // Finally we need support for FindToolWindow serviceProvider.AddService(typeof(SVsUIShell), GetWindowEnumerator0(), false); pane.SetSite(serviceProvider); } }
public void SetSite() { // Create the package IVsPackage package = new CloudFoundryVisualStudioPackage() as IVsPackage; Assert.IsNotNull(package, "The object does not implement IVsPackage"); // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); // Add site support for activity log BaseMock activityLogMock = new GenericMockFactory("MockVsActivityLog", new[] { typeof(Microsoft.VisualStudio.Shell.Interop.IVsActivityLog) }).GetInstance(); serviceProvider.AddService(typeof(Microsoft.VisualStudio.Shell.Interop.SVsActivityLog), activityLogMock, true); // Add site support to register editor factory BaseMock registerEditor = RegisterEditorMock.GetRegisterEditorsInstance(); serviceProvider.AddService(typeof(SVsRegisterEditors), registerEditor, false); // Site the package Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK"); // Unsite the package Assert.AreEqual(0, package.SetSite(null), "SetSite(null) did not return S_OK"); }
public void TestSccComand() { // Create the package BasicSccProvider package = new BasicSccProvider(); // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); // Need to mock a service implementing IVsRegisterScciProvider, because the scc provider will register with it IVsRegisterScciProvider registerScciProvider = MockRegisterScciProvider.GetBaseRegisterScciProvider(); serviceProvider.AddService(typeof(IVsRegisterScciProvider), registerScciProvider, true); // Site the package Assert.AreEqual(0, ((IVsPackage)package).SetSite(serviceProvider), "SetSite did not return S_OK"); // Test the scc command by toggleing it twice MethodInfo method = typeof(BasicSccProvider).GetMethod("OnSccCommand", BindingFlags.NonPublic | BindingFlags.Instance); TestSccCommand commandWell = new TestSccCommand(); CommandID cmdID = new CommandID(new System.Guid(), 0); MenuCommand command = new MenuCommand(new EventHandler(commandWell.OnSccCommand), cmdID); object result = method.Invoke(package, new object[] { command, null }); Assert.AreEqual(true, command.Checked, "OnSccCommand did not execute correctly"); result = method.Invoke(package, new object[] { command, null }); Assert.AreEqual(false, command.Checked, "OnSccCommand did not execute correctly"); }
public void SetSite() { // Create the package IVsPackage package = new SccProvider() as IVsPackage; Assert.IsNotNull(package, "The object does not implement IVsPackage"); // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); // Need to mock a service implementing IVsRegisterScciProvider, because the scc provider will register with it IVsRegisterScciProvider registerScciProvider = MockRegisterScciProvider.GetBaseRegisterScciProvider(); serviceProvider.AddService(typeof(IVsRegisterScciProvider), registerScciProvider, true); // Register solution events because the provider will try to subscribe to them MockSolution solution = new MockSolution(); serviceProvider.AddService(typeof(SVsSolution), solution as IVsSolution, true); // Register TPD service because the provider will try to subscribe to TPD IVsTrackProjectDocuments2 tpd = MockTrackProjectDocumentsProvider.GetTrackProjectDocuments() as IVsTrackProjectDocuments2; serviceProvider.AddService(typeof(SVsTrackProjectDocuments), tpd, true); // Site the package Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK"); // Unsite the package Assert.AreEqual(0, package.SetSite(null), "SetSite(null) did not return S_OK"); }
public void InitializationTest() { var mockServiceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); mockServiceProvider.AddService(typeof(SVsShellDebugger), _mocks.MockDebugger.Object, false); mockServiceProvider.AddService(typeof(SDTE), _mocks.MockDTE.Object, false); var package = new ReAttachPackage() as IVsPackage; Assert.IsNotNull(package, "The object does not implement IVsPackage"); Assert.AreEqual(0, package.SetSite(mockServiceProvider), "SetSite did not return S_OK"); Assert.AreEqual(0, package.SetSite(null), "SetSite(null) did not return S_OK"); var reAttachPackage = (ReAttachPackage)package; Assert.IsNotNull(reAttachPackage.Reporter); Assert.IsNotNull(reAttachPackage.Ui); Assert.IsNotNull(reAttachPackage.History); Assert.IsNotNull(reAttachPackage.Debugger); // Check for warnings/error. Note that one warning for empty registry on first load is expected. Assert.AreEqual(0, reAttachPackage.Reporter.ErrorCount, "ReAttach encountered errors during initialization."); Assert.AreEqual(1, reAttachPackage.Reporter.WarningCount, "ReAttach encountered warnings during initialization."); }
public void CreateEditorInstance() { VisualStudioHaskellPackage package = new VisualStudioHaskellPackage(); //Create the editor factory EditorFactory editorFactory = new EditorFactory(package); // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); serviceProvider.AddService(typeof(SLocalRegistry), (ILocalRegistry)LocalRegistryServiceMock.GetILocalRegistryInstance(), true); // Site the editor factory Assert.AreEqual(0, editorFactory.SetSite(serviceProvider), "SetSite did not return S_OK"); IntPtr ppunkDocView; IntPtr ppunkDocData; string pbstrEditorCaption = String.Empty; Guid pguidCmdUI = Guid.Empty; int pgrfCDW = 0; Assert.AreEqual(VSConstants.S_OK, editorFactory.CreateEditorInstance(VSConstants.CEF_OPENFILE, null, null, null, 0, IntPtr.Zero, out ppunkDocView, out ppunkDocData, out pbstrEditorCaption, out pguidCmdUI, out pgrfCDW)); }
public void InitializeMenuCommand() { // Create the package IVsPackage package = new ParametersXmlAddinPackage() as IVsPackage; Assert.IsNotNull(package, "The object does not implement IVsPackage"); // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); BaseMock activityLogMock = new GenericMockFactory("MockVsActivityLog", new[] { typeof(Microsoft.VisualStudio.Shell.Interop.IVsActivityLog) }).GetInstance(); serviceProvider.AddService( typeof(Microsoft.VisualStudio.Shell.Interop.SVsActivityLog), activityLogMock, true); // Site the package Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK"); //Verify that the menu command can be found CommandID menuCommandID = new CommandID(BlackMarble.ParametersXmlAddin.GuidList.guidParametersXmlAddinCmdSet, (int)BlackMarble.ParametersXmlAddin.PkgCmdIDList.cmdidGenerateParametersXmlFile); System.Reflection.MethodInfo info = typeof(Package).GetMethod("GetService", BindingFlags.Instance | BindingFlags.NonPublic); Assert.IsNotNull(info); OleMenuCommandService mcs = info.Invoke(package, new object[] { (typeof(IMenuCommandService)) }) as OleMenuCommandService; Assert.IsNotNull(mcs.FindCommand(menuCommandID)); }
public void ConsoleTextOfLineNoMarker() { string testString = "Test"; using (OleServiceProvider provider = new OleServiceProvider()) { BaseMock textLinesMock = MockFactories.TextBufferFactory.GetInstance(); textLinesMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLineText"), new EventHandler <CallbackArgs>(GetLineTextCallbackForConsoleTextOfLine)); textLinesMock["LineText"] = testString; textLinesMock["ExpectedLine"] = 1; textLinesMock["ExpectedStart"] = 0; textLinesMock["ExpectedEnd"] = 10; // Create a new local registry class. LocalRegistryMock mockRegistry = new LocalRegistryMock(); // Add the text buffer to the list of the classes that local registry can create. mockRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Add the local registry to the service provider. provider.AddService(typeof(SLocalRegistry), mockRegistry, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { IConsoleText consoleText = windowPane as IConsoleText; Assert.IsNull(consoleText.TextOfLine(1, -1, true)); Assert.IsNull(consoleText.TextOfLine(1, -1, false)); string text = consoleText.TextOfLine(1, 10, false); Assert.IsTrue(testString == text); } } }
public void InitializeConfigMenuCommands() { // Create the package IVsPackage package = new TestPackage(); Assert.IsNotNull(package, "The object does not implement IVsPackage"); // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); BaseMock uiShellService = MyToolWindowTest.UIShellServiceMock.GetUiShellInstanceCreateToolWin(); serviceProvider.AddService(typeof(SVsUIShell), uiShellService, false); BaseMock vsShellService = VSShellMock.GetVsShellInstance0(); serviceProvider.AddService(typeof(SVsShell), vsShellService, false); // Site the package Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK"); //Verify that the menu command can be found CommandID menuCommandID = new CommandID(GuidList.GUIDTestPackageCmdSet, (int)PkgCmdIDList.cmdTestSettings); MethodInfo info = typeof(Package).GetMethod("GetService", BindingFlags.Instance | BindingFlags.NonPublic); Assert.IsNotNull(info); OleMenuCommandService mcs = info.Invoke(package, new object[] { (typeof(IMenuCommandService)) }) as OleMenuCommandService; Assert.IsNotNull(mcs); Assert.IsNotNull(mcs.FindCommand(menuCommandID)); }
public void PackageCommands() { using (OleServiceProvider provider = OleServiceProvider.CreateOleServiceProviderWithBasicServices()) { IVsPackage package = null; try { // Create and site the package. package = new PythonConsolePackage() as IVsPackage; Assert.IsNotNull(package); int hr = package.SetSite(provider); Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded(hr)); // Get the command target from the package. IOleCommandTarget target = package as IOleCommandTarget; Assert.IsNotNull(target); CommandTargetHelper helper = new CommandTargetHelper(target); uint flags; Assert.IsTrue(helper.IsCommandSupported(GuidList.guidIronPythonConsoleCmdSet, PkgCmdIDList.cmdidIronPythonConsole, out flags)); Assert.IsTrue(0 != ((uint)OLECMDF.OLECMDF_SUPPORTED & flags)); Assert.IsTrue(0 != ((uint)OLECMDF.OLECMDF_ENABLED & flags)); Assert.IsTrue(0 == ((uint)OLECMDF.OLECMDF_INVISIBLE & flags)); } finally { if (null != package) { package.SetSite(null); package.Close(); } } } }
public void SetSite() { // Create the package IVsPackage package = new BooProjectPackage() as IVsPackage; Assert.IsNotNull(package, "The object does not implement IVsPackage"); // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); BaseMock activityLogMock = new GenericMockFactory( "MockVsActivityLog", new[] { typeof(Microsoft.VisualStudio.Shell.Interop.IVsActivityLog) } ).GetInstance(); serviceProvider.AddService( typeof(Microsoft.VisualStudio.Shell.Interop.SVsActivityLog), activityLogMock, true); // Site the package Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK"); // Unsite the package Assert.AreEqual(0, package.SetSite(null), "SetSite(null) did not return S_OK"); }
/// <summary> /// Retrieves the <see cref="IServiceLocator"/> for the given hierarchy. /// </summary> /// <exception cref="ArgumentNullException">The <paramref name="hierarchy"/> parameter was null.</exception> /// <exception cref="InvalidOperationException">The required <see cref="IComponentModel"/> service was not found.</exception> public static IServiceLocator GetServiceLocator(this IVsHierarchy hierarchy) { Guard.NotNull(nameof(hierarchy), hierarchy); IServiceProvider services; Ole.IServiceProvider site; // Still when succeedeed, site might be null if (ErrorHandler.Failed(hierarchy.GetSite(out site)) || site == null) { services = Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider; } else { services = new OleServiceProvider(site); } var components = services.GetService <SComponentModel, IComponentModel>(); try { return(components.GetService <IServiceLocatorProvider>().GetServiceLocator(hierarchy)); } catch (ImportCardinalityMismatchException ex) { throw new MissingDependencyException(Strings.ServiceLocator.MissingDependency(typeof(IServiceLocatorProvider)), ex); } }
public JavaProjectNode(ProjectPackage package) : base(package) { _sharedBuildOptions = new JavaBuildOptions(); CanProjectDeleteItems = true; OleServiceProvider.AddService(typeof(VSLangProj.VSProject), HandleCreateService, false); AddCatIdMapping(typeof(JavaFileNodeProperties), typeof(FileNodeProperties).GUID); }
/// <summary> /// This is the common function that executes the verification that the build /// messages are correctly written or omitted from the output according with /// the verbosity level. /// It takes as argument a function that set the verbosity for the logger. This /// delegate is needed because there are at least two different ways to set the /// verbosity: one reading it from the registry, the other setting it directly /// on the logger. /// </summary> private static void VerifyLoggingByVerbosity(LoggerVerbositySetter verbositySetter) { using (OleServiceProvider provider = new OleServiceProvider()) { using (TaskProvider task = new TaskProvider(new ServiceProvider(provider))) { IVsHierarchy hierarchy = MockFactories.HierarchyForLogger(provider); BaseMock mockOutput = MockFactories.OutputWindowPaneFactory.GetInstance(); // Create the logger and make sure that it points to the verbosity // registry key that we have deleted at the beginning of the test. IDELoggerProxy logger = new IDELoggerProxy(mockOutput as IVsOutputWindowPane, task, hierarchy); logger.SetBuildVerbosityRegistryRoot(TestVerbosityRoot); // Create the IEventSource that will be used to send messages to the logger BaseMock mockSource = MockFactories.CreateMSBuildEventSource(); // Now initialize the logger. logger.Initialize(mockSource as IEventSource); // Verify that the logger has installed an event handler for messages. Assert.IsNotNull(mockSource["MessageRaised"]); BuildMessageEventHandler messageHandler = (BuildMessageEventHandler)mockSource["MessageRaised"]; foreach (VerbosityImportancePair expected in expectedVerbosityImportancePair) { // Because the IDEBuildLogger caches its Verbosity setting after reading it // from the registry, we need to clear the cached value before calling the // verbositySetter, which may set verbosity by changing the registry value. logger.ClearVerbosityCache(); // Set the verbosity of the logger. verbositySetter(logger, expected.Verbosity); // Create a message of the expected importance. BuildMessageEventArgs message = new BuildMessageEventArgs("message", "help", "sender", expected.Importance); // Reset the counter of the calls to the output window pane. mockOutput.ResetAllFunctionCalls(); // Execute the message event handler messageHandler.Invoke(mockSource, message); System.Windows.Forms.Application.DoEvents(); // Verify that the output pane was used only if the expected result is that // something should be printed on the output. if (expected.ShouldPrint) { Assert.IsTrue(mockOutput.TotalCallsAllFunctions() > 0); } else { Assert.AreEqual <int>(mockOutput.TotalCallsAllFunctions(), 0); } } } } }
public void ReadOnlyRegionAfterWrite() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.CreateBufferWithMarker(); // Add the buffer to the local registry. LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the console window. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Get the stream from the window pane. System.IO.Stream consoleStream = CommandWindowHelper.ConsoleStream(windowPane); Assert.IsNotNull(consoleStream); // Set a return value for GetLastLineIndex textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLastLineIndex"), new object[] { 0, 12, 35 }); // Write some text on the stream. System.IO.StreamWriter writer = new System.IO.StreamWriter(consoleStream); writer.Write(""); writer.Flush(); // Verify that the ResetSpan method for the text marker was called and that // the span is set to cover all the current buffer. BaseMock markerMock = (BaseMock)textLinesMock["LineMarker"]; Assert.IsTrue(1 == markerMock.FunctionCalls(string.Format("{0}.{1}", typeof(IVsTextLineMarker).FullName, "ResetSpan"))); TextSpan span = (TextSpan)markerMock["Span"]; Assert.IsTrue(0 == span.iStartLine); Assert.IsTrue(0 == span.iStartIndex); Assert.IsTrue(12 == span.iEndLine); Assert.IsTrue(35 == span.iEndIndex); // Change the end point of the buffer and try again. textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLastLineIndex"), new object[] { 0, 15, 3 }); writer.Write("abc"); writer.Flush(); Assert.IsTrue(2 == markerMock.FunctionCalls(string.Format("{0}.{1}", typeof(IVsTextLineMarker).FullName, "ResetSpan"))); span = (TextSpan)markerMock["Span"]; Assert.IsTrue(0 == span.iStartLine); Assert.IsTrue(0 == span.iStartIndex); Assert.IsTrue(15 == span.iEndLine); Assert.IsTrue(3 == span.iEndIndex); } } }
public void OptionsPagePackageTestInitialize() { testPackage = new OptionsPagePackageCS(); // Create a basic service provider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); AddBasicSiteSupport(serviceProvider); ((IVsPackage)testPackage).SetSite(serviceProvider); }
public void SetSite() { //Create the editor factory EditorFactory editorFactory = new EditorFactory(); // Create a basic service provider OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices(); // Site the editor factory Assert.AreEqual(0, editorFactory.SetSite(serviceProvider), "SetSite did not return S_OK"); }
public BooProjectNode() { OleServiceProvider.AddService(typeof(EnvDTE.Project), new OleServiceProvider.ServiceCreatorCallback(CreateServices), false); OleServiceProvider.AddService(typeof(VSProject), new OleServiceProvider.ServiceCreatorCallback(CreateServices), false); OleServiceProvider.AddService(typeof(SVsDesignTimeAssemblyResolution), this, false); SupportsProjectDesigner = true; CanProjectDeleteItems = true; imageOffset = InitializeImageList(); compilerManager = new CompilerManager(this); }
public void TokensWithSpace() { using (OleServiceProvider provider = new OleServiceProvider()) { ResetScopeState(); // Create a mock engine provider. BaseMock mockEngineProvider = MockFactories.EngineProviderFactory.GetInstance(); // Create a mock engine. BaseMock mockEngine = MockFactories.EngineFactory.GetInstance(); // Set this engine as the one returned from the GetSharedEngine of the engine provider. mockEngineProvider.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IPythonEngineProvider), "GetSharedEngine"), new object[] { (IEngine)mockEngine }); // Add the engine provider to the list of the services. provider.AddService(typeof(IPythonEngineProvider), mockEngineProvider, false); // Create the scanner for this test. BaseMock scannerMock = MockFactories.ScannerFactory.GetInstance(); scannerMock["Iteration"] = 0; TokenInfo[] tokens = new TokenInfo[2]; tokens[0] = new TokenInfo(); tokens[0].StartIndex = 0; tokens[0].EndIndex = 2; tokens[0].Trigger = TokenTriggers.None; tokens[1] = new TokenInfo(); tokens[1].StartIndex = 4; tokens[1].EndIndex = 4; tokens[1].Trigger = TokenTriggers.MemberSelect; scannerMock["Tokens"] = tokens; scannerMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IScanner).FullName, "ScanTokenAndProvideInfoAboutIt"), new EventHandler<CallbackArgs>(StandardScannerCallback)); Declarations declarations = ExecuteGetDeclarations("dte .", scannerMock as IScanner, provider); Assert.IsTrue(0 == declarations.GetCount()); Assert.IsTrue(0 == mockEngine.TotalCallsAllFunctions()); } }