public static void AddBasicSiteSupport(Microsoft.VsSDK.UnitTestLibrary.OleServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } // Add solution Support BaseMock solution = MockServicesProvider.GetSolutionFactoryInstance(); serviceProvider.AddService(typeof(IVsSolution), solution, false); //Add site support for ILocalRegistry BaseMock localRegistry = MockServicesProvider.GetLocalRegistryInstance(); serviceProvider.AddService(typeof(SLocalRegistry), (ILocalRegistry)localRegistry, false); // 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 RegisterProjectTypes BaseMock mock = MockServicesProvider.GetRegisterProjectInstance(); serviceProvider.AddService(typeof(SVsRegisterProjectTypes), mock, false); // Add site support for VsShell BaseMock vsShell = MockServicesProvider.GetVsShellInstance0(); serviceProvider.AddService(typeof(SVsShell), vsShell, false); // Add site support for SolutionBuildManager service BaseMock solutionBuildManager = MockServicesProvider.GetSolutionBuildManagerInstance0(); serviceProvider.AddService(typeof(SVsSolutionBuildManager), solutionBuildManager, false); }
public void TestFlushWithException() { BaseMock mockBuffer = MockFactories.CreateBufferWithMarker(); mockBuffer.AddMethodCallback(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "ReplaceLines"), new EventHandler <CallbackArgs>(ReplaceLinesThrow)); bool exceptionThrown = false; try { using (Stream stream = CreateTextBufferStream((IVsTextLines)mockBuffer)) { string test = "Test Line"; using (StreamWriter writer = new StreamWriter(stream)) { writer.Write(test); writer.Flush(); } } } catch (TestStreamException) { exceptionThrown = true; } catch (System.Reflection.TargetInvocationException e) { TestStreamException inner = e.InnerException as TestStreamException; if (null != inner) { exceptionThrown = true; } } Assert.IsTrue(exceptionThrown); int lockCount = mockBuffer.FunctionCalls(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "LockBuffer")); int unlockCount = mockBuffer.FunctionCalls(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "UnlockBuffer")); Assert.IsTrue(lockCount == unlockCount); }
public void ShowToolwindowNegativeTest() { IVsPackage package = new TestPackage() 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); 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"); MethodInfo method = typeof(TestPackage).GetMethod("ShowTestList", BindingFlags.NonPublic | BindingFlags.Instance); //ShowToolWindow throw NotSupportException but the Exception is converted during the //call of invoke method object result = method.Invoke(package, new object[] { null, null }); }
public void TextViewCreation() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.TextBufferFactory.GetInstance(); LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Define the mock object for the text view. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); textViewMock.AddMethodCallback(string.Format("{0}.{1}", typeof(IObjectWithSite).FullName, "SetSite"), new EventHandler <CallbackArgs>(TextViewSetSiteCallback)); textViewMock.AddMethodCallback(string.Format("{0}.{1}", typeof(IVsTextView).FullName, "Initialize"), new EventHandler <CallbackArgs>(TextViewInitializeCallback)); mockLocalRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the tool window. using (IDisposable disposableObject = CommandWindowHelper.CreateConsoleWindow(provider) as IDisposable) { IVsWindowPane windowPane = disposableObject as IVsWindowPane; Assert.IsNotNull(windowPane); // Call the CreatePaneWindow method that will force the creation of the text view. IntPtr newHwnd; Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded( windowPane.CreatePaneWindow(IntPtr.Zero, 0, 0, 0, 0, out newHwnd))); // Verify that the text view was used as expected. Assert.IsTrue(1 == textViewMock.FunctionCalls(string.Format("{0}.{1}", typeof(IObjectWithSite), "SetSite"))); Assert.IsTrue(1 == textViewMock.FunctionCalls(string.Format("{0}.{1}", typeof(IVsTextView), "Initialize"))); } } }
public void TestFlushFromUTF8() { BaseMock mockBuffer = MockFactories.CreateBufferWithMarker(); mockBuffer.AddMethodReturnValues(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLastLineIndex"), new object[] { 0, 11, 42 }); mockBuffer["Text"] = ""; mockBuffer.AddMethodCallback(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "ReplaceLines"), new EventHandler <CallbackArgs>(ReplaceLinesCallback)); using (Stream stream = CreateTextBufferStream((IVsTextLines)mockBuffer)) { string test = "� Test �"; using (StreamWriter writer = new StreamWriter(stream, System.Text.Encoding.UTF8)) { writer.Write(test); writer.Flush(); Assert.IsTrue((string)mockBuffer["Text"] == test); } } int lockCount = mockBuffer.FunctionCalls(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "LockBuffer")); int unlockCount = mockBuffer.FunctionCalls(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "UnlockBuffer")); Assert.IsTrue(lockCount == unlockCount); }
public void ValidateToolWindowShown() { IVsPackage package = new oop3Package() 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 to register editor factory BaseMock registerEditor = oop3_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"); MethodInfo method = typeof(oop3Package).GetMethod("ShowToolWindow", BindingFlags.NonPublic | BindingFlags.Instance); object result = method.Invoke(package, new object[] { null, null }); }
public void StandardConstructor() { using (OleServiceProvider provider = OleServiceProvider.CreateOleServiceProviderWithBasicServices()) { IVsPackage package = null; try { // Create a mock object for the text buffer. BaseMock textLinesMock = MockFactories.TextBufferFactory.GetInstance(); // 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); provider.AddService(typeof(SLocalRegistry), mockRegistry, false); // Now create a package object and site it. package = new PythonConsolePackage() as IVsPackage; package.SetSite(provider); // Create a console window using the standard constructor and verify that the // text buffer is created and sited. using (IDisposable consoleObject = CommandWindowHelper.CreateConsoleWindow() as IDisposable) { Assert.IsTrue(0 < textLinesMock.FunctionCalls(string.Format("{0}.{1}", typeof(IObjectWithSite).FullName, "SetSite"))); } } finally { if (null != package) { package.SetSite(null); package.Close(); } } } }
public void OnApplyTest() { SccProviderOptions target = new SccProviderOptions(); // Create a basic service provider using (OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices()) { // Mock the UIShell service to answer Cancel to the dialog invocation BaseMock mockUIShell = MockUiShellProvider.GetShowMessageBoxCancel(); serviceProvider.AddService(typeof(IVsUIShell), mockUIShell, true); // Create an ISite wrapper over the service provider SiteWrappedServiceProvider wrappedProvider = new SiteWrappedServiceProvider(serviceProvider); target.Site = wrappedProvider; Assembly shell = typeof(Microsoft.VisualStudio.Shell.DialogPage).Assembly; Type argtype = shell.GetType("Microsoft.VisualStudio.Shell.DialogPage+PageApplyEventArgs", true); MethodInfo method = typeof(SccProviderOptions).GetMethod("OnApply", BindingFlags.NonPublic | BindingFlags.Instance); object eventargs = shell.CreateInstance(argtype.FullName); method.Invoke(target, new object[] { eventargs }); } }
public virtual void Initialize() { serviceProvider = Microsoft.VsSDK.UnitTestLibrary.OleServiceProvider.CreateOleServiceProviderWithBasicServices(); // Solution Support serviceProvider.AddService(typeof(SVsSolution), MockIVsSolution.GetInstance(), false); // Project Types Support serviceProvider.AddService(typeof(SVsRegisterProjectTypes), MockIVsRegisterProjectTypes.GetInstance(), false); // UIShell Support BaseMock uiShell = MockIVsUIShell.GetInstance(); serviceProvider.AddService(typeof(SVsUIShell), (IVsUIShell)uiShell, false); serviceProvider.AddService(typeof(SVsUIShellOpenDocument), (IVsUIShellOpenDocument)uiShell, false); // Shell Support serviceProvider.AddService(typeof(SVsShell), MockIVsShell.GetInstance(), false); // Build Manager support serviceProvider.AddService(typeof(SVsSolutionBuildManager), MockIVsSolutionBuildManager.GetInstance(), false); // ILocalRegistry support serviceProvider.AddService(typeof(SLocalRegistry), (ILocalRegistry)MockILocalRegistry.GetInstance(), false); // SVsFileChangeEx support serviceProvider.AddService(typeof(SVsFileChangeEx), MockIVsFileChangeEx.GetInstance(), false); serviceProvider.AddService(typeof(ObjectExtenders), MockObjectExtenders.GetInstance(), false); }
public void TestTPDEvents() { int result = 0; SccProviderService target = GetSccProviderServiceInstance; solution.SolutionFile = Path.GetTempFileName(); MockIVsProject project = new MockIVsProject(Path.GetTempFileName()); solution.AddProject(project); Hashtable uncontrolled = new Hashtable(); uncontrolled[project as IVsSccProject2] = true; target.AddProjectsToSourceControl(ref uncontrolled, true); // In real live, a QueryEdit call on the project file would be necessary to add/rename/delete items // Add a new item and fire the appropriate events string pendingAddFile = Path.GetTempFileName(); VSQUERYADDFILERESULTS[] pSummaryResultAdd = new VSQUERYADDFILERESULTS[1]; VSQUERYADDFILERESULTS[] rgResultsAdd = new VSQUERYADDFILERESULTS[1]; result = target.OnQueryAddFiles(project as IVsProject, 1, new string[] { pendingAddFile }, null, pSummaryResultAdd, rgResultsAdd); Assert.AreEqual <int>(VSConstants.E_NOTIMPL, result); project.AddItem(pendingAddFile); result = target.OnAfterAddFilesEx(1, 1, new IVsProject[] { project as IVsProject }, new int[] { 0 }, new string[] { pendingAddFile }, null); Assert.AreEqual <int>(VSConstants.E_NOTIMPL, result); Assert.AreEqual(SourceControlStatus.scsUncontrolled, target.GetFileStatus(pendingAddFile), "Incorrect status returned"); // Checkin the pending add file target.AddFileToSourceControl(pendingAddFile); // Rename the item and verify the file remains is controlled string newName = pendingAddFile + ".renamed"; VSQUERYRENAMEFILERESULTS[] pSummaryResultRen = new VSQUERYRENAMEFILERESULTS[1]; VSQUERYRENAMEFILERESULTS[] rgResultsRen = new VSQUERYRENAMEFILERESULTS[1]; result = target.OnQueryRenameFiles(project as IVsProject, 1, new string[] { pendingAddFile }, new string[] { newName }, null, pSummaryResultRen, rgResultsRen); Assert.AreEqual <int>(VSConstants.E_NOTIMPL, result); project.RenameItem(pendingAddFile, newName); result = target.OnAfterRenameFiles(1, 1, new IVsProject[] { project as IVsProject }, new int[] { 0 }, new string[] { pendingAddFile }, new string[] { newName }, new VSRENAMEFILEFLAGS[] { VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags }); Assert.AreEqual <int>(VSConstants.S_OK, result); Assert.AreEqual(SourceControlStatus.scsUncontrolled, target.GetFileStatus(pendingAddFile), "Incorrect status returned"); Assert.AreEqual(SourceControlStatus.scsCheckedIn, target.GetFileStatus(newName), "Incorrect status returned"); // Mock the UIShell service to answer Cancel to the dialog invocation BaseMock mockUIShell = MockUiShellProvider.GetShowMessageBoxCancel(); serviceProvider.AddService(typeof(IVsUIShell), mockUIShell, true); // Try to delete the file from project; the delete should not be allowed VSQUERYREMOVEFILERESULTS[] pSummaryResultDel = new VSQUERYREMOVEFILERESULTS[1]; VSQUERYREMOVEFILERESULTS[] rgResultsDel = new VSQUERYREMOVEFILERESULTS[1]; result = target.OnQueryRemoveFiles(project as IVsProject, 1, new string[] { newName }, null, pSummaryResultDel, rgResultsDel); Assert.AreEqual <int>(VSConstants.S_OK, result); Assert.AreEqual <VSQUERYREMOVEFILERESULTS>(VSQUERYREMOVEFILERESULTS.VSQUERYREMOVEFILERESULTS_RemoveNotOK, pSummaryResultDel[0]); // Mock the UIShell service to answer Yes to the dialog invocation serviceProvider.RemoveService(typeof(IVsUIShell)); mockUIShell = MockUiShellProvider.GetShowMessageBoxYes(); serviceProvider.AddService(typeof(IVsUIShell), mockUIShell, true); // Try to delete the file from project; the delete should be allowed this time result = target.OnQueryRemoveFiles(project as IVsProject, 1, new string[] { newName }, null, pSummaryResultDel, rgResultsDel); Assert.AreEqual <int>(VSConstants.S_OK, result); Assert.AreEqual <VSQUERYREMOVEFILERESULTS>(VSQUERYREMOVEFILERESULTS.VSQUERYREMOVEFILERESULTS_RemoveOK, pSummaryResultDel[0]); // Remove the file from project project.RemoveItem(newName); result = target.OnAfterRemoveFiles(1, 1, new IVsProject[] { project as IVsProject }, new int[] { 0 }, new string[] { newName }, null); Assert.AreEqual <int>(VSConstants.E_NOTIMPL, result); }
public void TestOpenCloseControlled() { const string strProviderName = "Sample Source Control Provider:{B0BAC05D-2000-41D1-A6C3-704E6C1A3DE2}"; const string strSolutionPersistanceKey = "SampleSourceControlProviderSolutionProperties"; const string strSolutionUserOptionsKey = "SampleSourceControlProvider"; int result = 0; // Create a solution SccProviderService target = GetSccProviderServiceInstance; solution.SolutionFile = Path.GetTempFileName(); MockIVsProject project = new MockIVsProject(Path.GetTempFileName()); solution.AddProject(project); // Check solution props VSQUERYSAVESLNPROPS[] saveSolnProps = new VSQUERYSAVESLNPROPS[1]; result = sccProvider.QuerySaveSolutionProps(null, saveSolnProps); Assert.AreEqual(VSConstants.S_OK, result); Assert.AreEqual <VSQUERYSAVESLNPROPS>(VSQUERYSAVESLNPROPS.QSP_HasNoProps, saveSolnProps[0]); // Add the solution to source control. Hashtable uncontrolled = new Hashtable(); uncontrolled[project as IVsSccProject2] = true; target.AddProjectsToSourceControl(ref uncontrolled, true); // Solution should be dirty now result = sccProvider.QuerySaveSolutionProps(null, saveSolnProps); Assert.AreEqual(VSConstants.S_OK, result); Assert.AreEqual <VSQUERYSAVESLNPROPS>(VSQUERYSAVESLNPROPS.QSP_HasDirtyProps, saveSolnProps[0]); // Set the project offline so we'll have something to save in the "suo" stream target.ToggleOfflineStatus(project); // Force the provider to write the solution info into a stream IStream pOptionsStream = new ComStreamFromDataStream(new MemoryStream()) as IStream; sccProvider.WriteUserOptions(pOptionsStream, strSolutionUserOptionsKey); // Move the stream position to the beginning LARGE_INTEGER liOffset; liOffset.QuadPart = 0; ULARGE_INTEGER[] ulPosition = new ULARGE_INTEGER[1]; pOptionsStream.Seek(liOffset, 0, ulPosition); // Write solution props BaseMock propertyBag = MockPropertyBagProvider.GetWritePropertyBag(); sccProvider.WriteSolutionProps(null, strSolutionPersistanceKey, propertyBag as IPropertyBag); // Close the solution to clean up the scc status int pfCancel = 0; target.OnQueryCloseProject(project, 0, ref pfCancel); target.OnQueryCloseSolution(null, ref pfCancel); Assert.AreEqual(pfCancel, 0, "Solution close was canceled"); target.OnBeforeCloseProject(project, 0); // Theoretically the project should have called this, but especially after an add to scc, some projects forget to call it // target.UnregisterSccProject(project); target.OnBeforeCloseSolution(null); target.OnAfterCloseSolution(null); // Now attempt the "reopen" // The solution reads the solution properties propertyBag = MockPropertyBagProvider.GetReadPropertyBag(); sccProvider.ReadSolutionProps(null, null, null, strSolutionPersistanceKey, 1, propertyBag as IPropertyBag); // The solution reads the user options from the stream where they were written before sccProvider.ReadUserOptions(pOptionsStream, strSolutionUserOptionsKey); // Then the projects are opened and register with the provider target.RegisterSccProject(project, "Project's location", "AuxPath", Path.GetDirectoryName(project.ProjectFile), strProviderName); // solution event fired for this project target.OnAfterOpenProject(project, 0); // Then solution completes opening target.OnAfterOpenSolution(null, 0); Assert.IsTrue(target.IsProjectControlled(null), "The solution's controlled status was not correctly persisted or read from property bag"); Assert.IsTrue(target.IsProjectControlled(project), "The project's controlled status was not correctly set"); Assert.IsTrue(target.IsProjectOffline(project), "The project's offline status was incorrectly persisted or read from suo stream"); }
private static void TargetKindCallBack(object caller, CallbackArgs arguments) { BaseMock compiler = (BaseMock)caller; compiler["TargetKind"] = arguments.GetParameter(0); }
public void QueryEditQuerySaveTest() { uint pfEditVerdict; uint prgfMoreInfo; uint pdwQSResult; int result; SccProviderService target = GetSccProviderServiceInstance; // check the functions that are not implemented Assert.AreEqual((int)VSConstants.S_OK, (int)target.BeginQuerySaveBatch()); Assert.AreEqual((int)VSConstants.S_OK, (int)target.EndQuerySaveBatch()); Assert.AreEqual((int)VSConstants.S_OK, (int)target.DeclareReloadableFile("", 0, null)); Assert.AreEqual((int)VSConstants.S_OK, (int)target.DeclareUnreloadableFile("", 0, null)); Assert.AreEqual((int)VSConstants.S_OK, (int)target.OnAfterSaveUnreloadableFile("", 0, null)); Assert.AreEqual((int)VSConstants.S_OK, (int)target.IsReloadable("", out result)); Assert.AreEqual(1, result, "Not the right return value from IsReloadable"); // Create a basic service provider IVsShell shell = MockShellProvider.GetShellForCommandLine() as IVsShell; serviceProvider.AddService(typeof(IVsShell), shell, true); // Command line tests result = target.QueryEditFiles((uint)tagVSQueryEditFlags.QEF_ReportOnly, 1, new string[] { "Dummy.txt" }, null, null, out pfEditVerdict, out prgfMoreInfo); Assert.AreEqual(VSConstants.S_OK, result, "QueryEdit failed."); Assert.AreEqual((uint)tagVSQueryEditResult.QER_EditOK, pfEditVerdict, "QueryEdit failed."); Assert.AreEqual((uint)0, prgfMoreInfo, "QueryEdit failed."); result = target.QuerySaveFile("Dummy.txt", 0, null, out pdwQSResult); Assert.AreEqual(VSConstants.S_OK, result, "QuerySave failed."); Assert.AreEqual((uint)tagVSQuerySaveResult.QSR_SaveOK, pdwQSResult, "QueryEdit failed."); serviceProvider.RemoveService(typeof(SVsShell)); // UI mode tests shell = MockShellProvider.GetShellForUI() as IVsShell; serviceProvider.AddService(typeof(SVsShell), shell, true); // Edit of an uncontrolled file that doesn't exist on disk result = target.QueryEditFiles((uint)tagVSQueryEditFlags.QEF_ReportOnly, 1, new string[] { "Dummy.txt" }, null, null, out pfEditVerdict, out prgfMoreInfo); Assert.AreEqual(VSConstants.S_OK, result, "QueryEdit failed."); Assert.AreEqual((uint)tagVSQueryEditResult.QER_EditOK, pfEditVerdict, "QueryEdit failed."); Assert.AreEqual((uint)0, prgfMoreInfo, "QueryEdit failed."); // Mock a solution with a project and a file solution.SolutionFile = Path.GetTempFileName(); MockIVsProject project = new MockIVsProject(Path.GetTempFileName()); solution.AddProject(project); // Add only the project to source control. Hashtable uncontrolled = new Hashtable(); uncontrolled[project as IVsSccProject2] = true; target.AddProjectsToSourceControl(ref uncontrolled, false); // Check that solution file is not controlled Assert.AreEqual(SourceControlStatus.scsUncontrolled, target.GetFileStatus(solution.SolutionFile), "Incorrect status returned"); // Make the solution read-only on disk File.SetAttributes(solution.SolutionFile, FileAttributes.ReadOnly); // QueryEdit in report mode for uncontrolled readonly file result = target.QueryEditFiles((uint)tagVSQueryEditFlags.QEF_ReportOnly, 1, new string[] { solution.SolutionFile }, null, null, out pfEditVerdict, out prgfMoreInfo); Assert.AreEqual(VSConstants.S_OK, result, "QueryEdit failed."); Assert.AreEqual((uint)tagVSQueryEditResult.QER_EditNotOK, pfEditVerdict, "QueryEdit failed."); Assert.AreEqual((uint)(tagVSQueryEditResultFlags.QER_EditNotPossible | tagVSQueryEditResultFlags.QER_ReadOnlyNotUnderScc), prgfMoreInfo, "QueryEdit failed."); // QueryEdit in silent mode for uncontrolled readonly file result = target.QueryEditFiles((uint)tagVSQueryEditFlags.QEF_SilentMode, 1, new string[] { solution.SolutionFile }, null, null, out pfEditVerdict, out prgfMoreInfo); Assert.AreEqual(VSConstants.S_OK, result, "QueryEdit failed."); Assert.AreEqual((uint)tagVSQueryEditResult.QER_EditNotOK, pfEditVerdict, "QueryEdit failed."); Assert.AreEqual((uint)(tagVSQueryEditResultFlags.QER_NoisyPromptRequired), (uint)(tagVSQueryEditResultFlags.QER_NoisyPromptRequired) & prgfMoreInfo, "QueryEdit failed."); // Mock the UIShell service to answer Yes to the dialog invocation BaseMock mockUIShell = MockUiShellProvider.GetShowMessageBoxYes(); serviceProvider.AddService(typeof(IVsUIShell), mockUIShell, true); // QueryEdit for uncontrolled readonly file: allow the edit and make the file read-write result = target.QueryEditFiles(0, 1, new string[] { solution.SolutionFile }, null, null, out pfEditVerdict, out prgfMoreInfo); Assert.AreEqual(VSConstants.S_OK, result, "QueryEdit failed."); Assert.AreEqual((uint)tagVSQueryEditResult.QER_EditOK, pfEditVerdict, "QueryEdit failed."); Assert.AreEqual((uint)0, prgfMoreInfo, "QueryEdit failed."); Assert.AreEqual <FileAttributes>(FileAttributes.Normal, File.GetAttributes(solution.SolutionFile), "File was not made writable"); serviceProvider.RemoveService(typeof(IVsUIShell)); // QueryEdit in report mode for controlled readonly file result = target.QueryEditFiles((uint)tagVSQueryEditFlags.QEF_ReportOnly, 1, new string[] { project.ProjectFile }, null, null, out pfEditVerdict, out prgfMoreInfo); Assert.AreEqual(VSConstants.S_OK, result, "QueryEdit failed."); Assert.AreEqual((uint)tagVSQueryEditResult.QER_EditNotOK, pfEditVerdict, "QueryEdit failed."); Assert.AreEqual((uint)(tagVSQueryEditResultFlags.QER_EditNotPossible | tagVSQueryEditResultFlags.QER_ReadOnlyUnderScc), prgfMoreInfo, "QueryEdit failed."); // QueryEdit in silent mode for controlled readonly file: should allow the edit and make the file read-write result = target.QueryEditFiles((uint)tagVSQueryEditFlags.QEF_SilentMode, 1, new string[] { project.ProjectFile }, null, null, out pfEditVerdict, out prgfMoreInfo); Assert.AreEqual(VSConstants.S_OK, result, "QueryEdit failed."); Assert.AreEqual((uint)tagVSQueryEditResult.QER_EditOK, pfEditVerdict, "QueryEdit failed."); Assert.AreEqual((uint)tagVSQueryEditResultFlags.QER_MaybeCheckedout, prgfMoreInfo, "QueryEdit failed."); Assert.AreEqual <FileAttributes>(FileAttributes.Normal, File.GetAttributes(solution.SolutionFile), "File was not made writable"); serviceProvider.RemoveService(typeof(IVsUIShell)); }
private static void EventSourceAddTaskFinished(object sender, CallbackArgs args) { BaseMock mock = (BaseMock)sender; mock["TaskFinished"] = args.GetParameter(0); }
public void EventsOutOfSequence() { // Make sure that the registry key is no present so that we can set the verbosity. DeleteVerbosityKey(); using (OleServiceProvider provider = new OleServiceProvider()) { using (TaskProvider task = new TaskProvider(new ServiceProvider(provider))) { IVsHierarchy hierarchy = MockFactories.HierarchyForLogger(provider); IVsOutputWindowPane output = MockFactories.OutputPaneWithStringFunctions(); BaseMock mockOutput = (BaseMock)output; // Create the logger and make sure that it points to the verbosity IDELoggerProxy logger = new IDELoggerProxy(output, 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 and // build events. Assert.IsNotNull(mockSource["MessageRaised"]); BuildMessageEventHandler messageHandler = (BuildMessageEventHandler)mockSource["MessageRaised"]; Assert.IsNotNull(mockSource["BuildStarted"]); BuildStartedEventHandler buildStartedHandler = (BuildStartedEventHandler)mockSource["BuildStarted"]; Assert.IsNotNull(mockSource["BuildFinished"]); BuildFinishedEventHandler buildFinishedHandler = (BuildFinishedEventHandler)mockSource["BuildFinished"]; Assert.IsNotNull(mockSource["TaskStarted"]); TaskStartedEventHandler taskStartedHandler = (TaskStartedEventHandler)mockSource["TaskStarted"]; Assert.IsNotNull(mockSource["TaskFinished"]); TaskFinishedEventHandler taskFinishedHandler = (TaskFinishedEventHandler)mockSource["TaskFinished"]; // Create the arguments for the events and the delegates. BuildMessageEventArgs messageArgs = new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Normal); SendEventFunction sendMessage = delegate { messageHandler.Invoke(mockSource, messageArgs); }; // BuildStartedEventArgs startBuildArgs = new BuildStartedEventArgs("Start Build", "help"); SendEventFunction sendStartBuild = delegate { buildStartedHandler.Invoke(mockSource, startBuildArgs); }; // BuildFinishedEventArgs finishBuildArgs = new BuildFinishedEventArgs("End Build", "help", true); SendEventFunction sendEndBuild = delegate { buildFinishedHandler.Invoke(mockSource, finishBuildArgs); }; // TaskStartedEventArgs startTaskArgs = new TaskStartedEventArgs("Start Task", null, null, null, null); SendEventFunction sendStartTask = delegate { taskStartedHandler.Invoke(mockSource, startTaskArgs); }; // TaskFinishedEventArgs endTaskArgs = new TaskFinishedEventArgs("End Task", null, null, null, null, true); SendEventFunction sendEndTask = delegate { taskFinishedHandler.Invoke(mockSource, endTaskArgs); }; // Set the verbosity to Diagnostic so that all the messages are written. logger.Verbosity = LoggerVerbosity.Diagnostic; List <SendEventFunction>[] events = new List <SendEventFunction>[] { new List <SendEventFunction>(new SendEventFunction[] { sendMessage, sendEndBuild, sendStartBuild }), new List <SendEventFunction>(new SendEventFunction[] { sendStartBuild, sendEndTask, sendEndBuild, sendStartTask }), new List <SendEventFunction>(new SendEventFunction[] { sendStartTask, sendStartBuild, sendEndTask, sendEndBuild }), new List <SendEventFunction>(new SendEventFunction[] { sendEndBuild, sendStartTask, sendEndTask, sendStartBuild }), new List <SendEventFunction>(new SendEventFunction[] { sendEndBuild, sendEndTask, sendStartTask, sendStartBuild }), new List <SendEventFunction>(new SendEventFunction[] { sendEndTask, sendEndBuild, sendStartTask, sendStartBuild }), }; // Call the functions. Note that here we don't check for the actual text printed on the output, // but we simply verify that the logger can handle the events without exceptions. foreach (List <SendEventFunction> sendFunctions in events) { output.Clear(); foreach (SendEventFunction func in sendFunctions) { func(); } } } } }
private static void OutputAssemblyCallBack(object caller, CallbackArgs arguments) { BaseMock compiler = (BaseMock)caller; compiler["OutputAssembly"] = arguments.GetParameter(0); }
private static void EventSourceAddMessageRaised(object sender, CallbackArgs args) { BaseMock mock = (BaseMock)sender; mock["MessageRaised"] = args.GetParameter(0); }
public void ConsoleCreation() { using (OleServiceProvider provider = OleServiceProvider.CreateOleServiceProviderWithBasicServices()) { // In order to create a console window we have to add the text buffer to the // local registry. // Create a mock object for the text buffer. BaseMock textLinesMock = MockFactories.TextBufferFactory.GetInstance(); // 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); // Define the mock object for the text view. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); mockRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry mock to the service provider. provider.AddService(typeof(SLocalRegistry), mockRegistry, false); // Create a mock UIShell to be able to create the tool window. BaseMock uiShell = MockFactories.UIShellFactory.GetInstance(); uiShell["Frame"] = MockFactories.WindowFrameFactory.GetInstance() as IVsWindowFrame; uiShell.AddMethodCallback( string.Format("{0}.{1}", typeof(IVsUIShell), "CreateToolWindow"), new EventHandler <CallbackArgs>(CreateToolwindowCallback)); provider.AddService(typeof(SVsUIShell), uiShell, false); IVsPackage package = null; try { // Create the package. package = new PythonConsolePackage() as IVsPackage; Assert.IsNotNull(package); // Make sure that the static variable about the global service provider is null; FieldInfo globalProvider = typeof(Microsoft.VisualStudio.Shell.Package).GetField("_globalProvider", BindingFlags.Static | BindingFlags.NonPublic); globalProvider.SetValue(null, null); // Site it. 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); helper.ExecCommand(GuidList.guidIronPythonConsoleCmdSet, PkgCmdIDList.cmdidIronPythonConsole); } finally { if (null != package) { package.SetSite(null); package.Close(); } } } }
public void ConsoleTextOfLineWithMarker() { string testString1 = "Test 1"; string testString2 = "Test 2"; using (OleServiceProvider provider = new OleServiceProvider()) { BaseMock textLinesMock = MockFactories.CreateBufferWithMarker(); textLinesMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLineText"), new EventHandler <CallbackArgs>(GetLineTextCallbackForConsoleTextOfLine)); // 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) { // Make sure that the text marker is created. CommandWindowHelper.EnsureConsoleTextMarker(windowPane); // Set the span of the marker. TextSpan span = new TextSpan(); span.iStartLine = 0; span.iStartIndex = 0; span.iEndLine = 3; span.iEndIndex = 5; BaseMock markerMock = (BaseMock)textLinesMock["LineMarker"]; markerMock["Span"] = span; IConsoleText consoleText = windowPane as IConsoleText; // Verify the case that the requested line is all inside the // read only region. textLinesMock["LineText"] = testString1; textLinesMock["ExpectedLine"] = 1; textLinesMock["ExpectedStart"] = 0; textLinesMock["ExpectedEnd"] = 10; Assert.IsNull(consoleText.TextOfLine(1, 10, true)); string text = consoleText.TextOfLine(1, 10, false); Assert.IsTrue(text == testString1); // Now ask for some text inside the read-only region, but on its last line. textLinesMock["LineText"] = testString2; textLinesMock["ExpectedLine"] = 3; textLinesMock["ExpectedStart"] = 0; textLinesMock["ExpectedEnd"] = 4; Assert.IsNull(consoleText.TextOfLine(3, 4, true)); text = consoleText.TextOfLine(3, 4, false); Assert.IsTrue(text == testString2); // Now the text is part inside and part outside the read-only region. textLinesMock["LineText"] = testString1; textLinesMock["ExpectedLine"] = 3; textLinesMock["ExpectedStart"] = 5; textLinesMock["ExpectedEnd"] = 10; text = consoleText.TextOfLine(3, 10, true); Assert.IsTrue(testString1 == text); textLinesMock["LineText"] = testString2; textLinesMock["ExpectedLine"] = 3; textLinesMock["ExpectedStart"] = 0; textLinesMock["ExpectedEnd"] = 10; text = consoleText.TextOfLine(3, 10, false); Assert.IsTrue(text == testString2); // Now the line has no intersection with the read-only region. textLinesMock["LineText"] = testString1; textLinesMock["ExpectedLine"] = 4; textLinesMock["ExpectedStart"] = 0; textLinesMock["ExpectedEnd"] = 10; text = consoleText.TextOfLine(4, 10, true); Assert.IsTrue(testString1 == text); textLinesMock["LineText"] = testString2; textLinesMock["ExpectedLine"] = 4; textLinesMock["ExpectedStart"] = 0; textLinesMock["ExpectedEnd"] = 10; text = consoleText.TextOfLine(4, 10, false); Assert.IsTrue(text == testString2); } } }
public PackageTestEnvironment() { // Create the project project = new ProjectTestClass(); // Site the project services = Microsoft.VsSDK.UnitTestLibrary.OleServiceProvider.CreateOleServiceProviderWithBasicServices(); LocalRegistryMock localRegistry = new LocalRegistryMock(); localRegistry.RegistryRoot = @"Software\Microsoft\VisualStudio\9.0"; services.AddService(typeof(SLocalRegistry), localRegistry, true); BaseMock mockConfigMgr = ConfigurationManagerFactory.GetInstance(); BaseMock extensibility = ExtensibilityFactory.GetInstance(); extensibility.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsExtensibility3).FullName, "GetConfigMgr"), new object[] { 0, null, null, mockConfigMgr }); services.AddService(typeof(IVsExtensibility), extensibility, false); project.SetSite(services); // Init the msbuild engine if (null == initEngine) { initEngine = typeof(VisualStudio.Project.Utilities).GetMethod("InitializeMsBuildEngine", BindingFlags.NonPublic | BindingFlags.Static); } Microsoft.Build.Evaluation.ProjectCollection engine = initEngine.Invoke(null, new object[2] { null, services }) as Microsoft.Build.Evaluation.ProjectCollection; Assert.IsNotNull(engine, "MSBuild Engine could not be initialized"); // Retrieve the project file content, load it and save it string fullpath = Path.Combine(new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent.FullName, "TestProject.proj"); if (string.IsNullOrEmpty(projectXml)) { projectXml = Properties.Resources.TestProject; using (TextWriter writer = new StreamWriter(fullpath)) { writer.Write(projectXml); } } // Init the msbuild project if (null == initProject) { initProject = typeof(VisualStudio.Project.Utilities).GetMethod("InitializeMsBuildProject", BindingFlags.NonPublic | BindingFlags.Static); } Microsoft.Build.Evaluation.Project buildProject = initProject.Invoke(null, new object[2] { engine, fullpath }) as Microsoft.Build.Evaluation.Project; Assert.IsNotNull(buildProject, "MSBuild project not initialized correctly in InitializeMsBuildProject"); //Verify that we can set the build project on the projectnode PropertyInfo buildProjectInfo = typeof(VisualStudio.Project.ProjectNode).GetProperty("BuildProject", BindingFlags.Instance | BindingFlags.NonPublic); buildProjectInfo.SetValue(project, buildProject, new object[0]); // Now the project is opened, so we can update its internal variable. if (null == projectOpened) { projectOpened = typeof(VisualStudio.Project.ProjectNode).GetField("projectOpened", BindingFlags.Instance | BindingFlags.NonPublic); } projectOpened.SetValue(project, true); }
private void SetUpNumberDefaults(AttributeMetadata attribute, BaseMock selectedMock) { if (selectedMock is BinomialDistribution || selectedMock is FixedNumber) { return; } switch (attribute) { case DecimalAttributeMetadata decAttr: if (selectedMock is NormalDistribution normalDistribution1) { normalDistribution1.Decimals = decAttr.Precision.GetValueOrDefault(); return; } var decMock = (Number)selectedMock; decMock.Decimals = decAttr.Precision.GetValueOrDefault(); decMock.Max = decAttr.MaxValue.GetValueOrDefault(); decMock.Min = decAttr.MinValue.GetValueOrDefault(); break; case DoubleAttributeMetadata doubleAttr: if (selectedMock is NormalDistribution distribution1) { distribution1.Decimals = doubleAttr.Precision.GetValueOrDefault(); return; } var dblMock = (Number)selectedMock; //Fixed numbers dblMock.Decimals = doubleAttr.Precision.GetValueOrDefault(); dblMock.Max = (decimal)doubleAttr.MaxValue.GetValueOrDefault(); dblMock.Min = (decimal)doubleAttr.MinValue.GetValueOrDefault(); break; case IntegerAttributeMetadata intAttr: if (selectedMock is NormalDistribution mock) { mock.Decimals = 0; return; } var intMock = (Number)selectedMock; intMock.Decimals = 0; intMock.Max = intAttr.MaxValue.GetValueOrDefault(); intMock.Min = intAttr.MinValue.GetValueOrDefault(); break; case MoneyAttributeMetadata moneyAttr: if (selectedMock is NormalDistribution normalDistribution) { normalDistribution.Decimals = moneyAttr.Precision.GetValueOrDefault(); return; } var moneyMock = (Number)selectedMock; moneyMock.Decimals = moneyAttr.Precision.GetValueOrDefault(); moneyMock.Max = (decimal)moneyAttr.MaxValue.GetValueOrDefault(); moneyMock.Min = (decimal)moneyAttr.MinValue.GetValueOrDefault(); break; case BigIntAttributeMetadata bigIntAttr: if (selectedMock is NormalDistribution distribution) { distribution.Decimals = 0; return; } var bigIntMock = (Number)selectedMock; bigIntMock.Decimals = 0; bigIntMock.Max = bigIntAttr.MaxValue.GetValueOrDefault(); bigIntMock.Min = bigIntAttr.MinValue.GetValueOrDefault(); break; default: break; } }
public void Initialize() { _baseMock = new BaseMock("A Key", "http://google.com"); }
public void TestSccMenuCommands() { int result = 0; Guid badGuid = new Guid(); Guid guidCmdGroup = GuidList.guidSccProviderCmdSet; OLECMD[] cmdAddToScc = new OLECMD[1]; cmdAddToScc[0].cmdID = CommandId.icmdAddToSourceControl; OLECMD[] cmdCheckin = new OLECMD[1]; cmdCheckin[0].cmdID = CommandId.icmdCheckin; OLECMD[] cmdCheckout = new OLECMD[1]; cmdCheckout[0].cmdID = CommandId.icmdCheckout; OLECMD[] cmdUseSccOffline = new OLECMD[1]; cmdUseSccOffline[0].cmdID = CommandId.icmdUseSccOffline; OLECMD[] cmdViewToolWindow = new OLECMD[1]; cmdViewToolWindow[0].cmdID = CommandId.icmdViewToolWindow; OLECMD[] cmdToolWindowToolbarCommand = new OLECMD[1]; cmdToolWindowToolbarCommand[0].cmdID = CommandId.icmdToolWindowToolbarCommand; OLECMD[] cmdUnsupported = new OLECMD[1]; cmdUnsupported[0].cmdID = 0; // Initialize the provider, etc SccProviderService target = GetSccProviderServiceInstance; // Mock a service implementing IVsMonitorSelection BaseMock monitorSelection = MockIVsMonitorSelectionFactory.GetMonSel(); serviceProvider.AddService(typeof(IVsMonitorSelection), monitorSelection, true); // Commands that don't belong to our package should not be supported result = _sccProvider.QueryStatus(ref badGuid, 1, cmdAddToScc, IntPtr.Zero); Assert.AreEqual((int)Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED, result); // The command should be invisible when there is no solution VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE, cmdAddToScc); // Activate the provider and test the result target.SetActive(); Assert.AreEqual(true, target.Active, "Microsoft.Samples.VisualStudio.SourceControlIntegration.SccProvider.SccProviderService.Active was not reported correctly."); // The commands should be invisible when there is no solution VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE, cmdUseSccOffline); // Commands that don't belong to our package should not be supported result = _sccProvider.QueryStatus(ref guidCmdGroup, 1, cmdUnsupported, IntPtr.Zero); Assert.AreEqual((int)Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED, result); // Deactivate the provider and test the result target.SetInactive(); Assert.AreEqual(false, target.Active, "Microsoft.Samples.VisualStudio.SourceControlIntegration.SccProvider.SccProviderService.Active was not reported correctly."); // Create a solution solution.SolutionFile = Path.GetTempFileName(); MockIVsProject project = new MockIVsProject(Path.GetTempFileName()); project.AddItem(Path.GetTempFileName()); solution.AddProject(project); // The commands should be invisible when the provider is not active VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE, cmdUseSccOffline); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE, cmdViewToolWindow); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE, cmdToolWindowToolbarCommand); // Activate the provider and test the result target.SetActive(); Assert.AreEqual(true, target.Active, "Microsoft.Samples.VisualStudio.SourceControlIntegration.SccProvider.SccProviderService.Active was not reported correctly."); // The command should be visible but disabled now, except the toolwindow ones VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdUseSccOffline); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdViewToolWindow); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdToolWindowToolbarCommand); // Set selection to solution node VSITEMSELECTION selSolutionRoot; selSolutionRoot.pHier = _solution as IVsHierarchy; selSolutionRoot.itemid = VSConstants.VSITEMID_ROOT; monitorSelection["Selection"] = new VSITEMSELECTION[] { selSolutionRoot }; // The add command should be available, rest should be disabled VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdUseSccOffline); // Still solution hierarchy, but other way selSolutionRoot.pHier = null; selSolutionRoot.itemid = VSConstants.VSITEMID_ROOT; monitorSelection["Selection"] = new VSITEMSELECTION[] { selSolutionRoot }; // The add command should be available, rest should be disabled VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdUseSccOffline); // Set selection to project node VSITEMSELECTION selProjectRoot; selProjectRoot.pHier = project as IVsHierarchy; selProjectRoot.itemid = VSConstants.VSITEMID_ROOT; monitorSelection["Selection"] = new VSITEMSELECTION[] { selProjectRoot }; // The add command should be available, rest should be disabled VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdUseSccOffline); // Set selection to project item VSITEMSELECTION selProjectItem; selProjectItem.pHier = project as IVsHierarchy; selProjectItem.itemid = 0; monitorSelection["Selection"] = new VSITEMSELECTION[] { selProjectItem }; // The add command should be available, rest should be disabled VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdUseSccOffline); // Set selection to project and item node and add project to scc monitorSelection["Selection"] = new VSITEMSELECTION[] { selProjectRoot, selProjectItem }; VerifyCommandExecution(cmdAddToScc); // The add command and checkin should be disabled, rest should be available now VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdUseSccOffline); // Checkout the project VerifyCommandExecution(cmdCheckout); // The add command and checkout should be disabled, rest should be available now VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdUseSccOffline); // Select the solution monitorSelection["Selection"] = new VSITEMSELECTION[] { selSolutionRoot }; // The checkout and offline should be disabled, rest should be available now VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdUseSccOffline); // Checkin the project VerifyCommandExecution(cmdCheckin); // The add command and checkout should be enabled, rest should be disabled VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdUseSccOffline); // Add the solution to scc VerifyCommandExecution(cmdAddToScc); // The add command and checkin should be disabled, rest should be available now VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdUseSccOffline); // Select the solution and project monitorSelection["Selection"] = new VSITEMSELECTION[] { selSolutionRoot, selProjectRoot }; // Take the project and solution offline VerifyCommandExecution(cmdUseSccOffline); // The offline command should be latched VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_LATCHED, cmdUseSccOffline); // Select the solution only monitorSelection["Selection"] = new VSITEMSELECTION[] { selSolutionRoot }; // Take the solution online VerifyCommandExecution(cmdUseSccOffline); // The offline command should be normal again VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdUseSccOffline); // Select the solution and project monitorSelection["Selection"] = new VSITEMSELECTION[] { selSolutionRoot, selProjectRoot }; // The offline command should be disabled for mixed selection VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdUseSccOffline); // Add a new item to the project project.AddItem(Path.GetTempFileName()); // Select the new item selProjectItem.pHier = project as IVsHierarchy; selProjectItem.itemid = 1; monitorSelection["Selection"] = new VSITEMSELECTION[] { selProjectItem }; // The add command and checkout should be disabled, rest should be available now VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_LATCHED, cmdUseSccOffline); // Checkin the new file (this should do an add) VerifyCommandExecution(cmdCheckin); // The add command and checkout should be disabled, rest should be available now VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdAddToScc); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED, cmdCheckin); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED, cmdCheckout); VerifyCommandStatus(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_LATCHED, cmdUseSccOffline); }
private static void ReferencedAssembliesCallBack(object caller, CallbackArgs arguments) { BaseMock compiler = (BaseMock)caller; compiler["ReferencedAssemblies"] = arguments.GetParameter(0); }
public List <ExpandoObject> GetData(ExpandoObject exo, int count) { if (count == 0) { return(new List <ExpandoObject>()); } List <Dictionary <string, object> > fields = new List <Dictionary <string, object> >(); foreach (var property in exo) { BaseMock mock = (BaseMock)property.Value; var field = mock.GetField(); if (!field.ContainsKey("Name")) { field.Add("Name", property.Key); } fields.Add(field); } var jsonSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var jsonString = JsonConvert.SerializeObject( fields, Formatting.None, jsonSettings); var url = string.Format(MockarooApiUrl, _apiKey, count); var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(url), Content = new StringContent(jsonString) }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string responseContent; var handler = new HttpClientHandler(); using (var client = new HttpClient(handler)) { var response = client.SendAsync(request).Result; responseContent = response.Content.ReadAsStringAsync().Result; if (response.StatusCode != HttpStatusCode.OK) { var errObj = JsonConvert.DeserializeObject <JObject>( response.Content.ReadAsStringAsync().Result); throw new Exception(errObj.GetValue("error").ToString()); } // data = count == 1 // ? new[] { JsonConvert.DeserializeObject<T>(responseContent) }.AsEnumerable() // : JsonConvert.DeserializeObject<IEnumerable<T>>(responseContent); } var expConverter = new ExpandoObjectConverter(); return(JsonConvert.DeserializeObject <List <ExpandoObject> >(responseContent, expConverter)); // return JsonConvert.DeserializeObject(responseContent); }
private static void MainFileCallBack(object caller, CallbackArgs arguments) { BaseMock compiler = (BaseMock)caller; compiler["MainFile"] = arguments.GetParameter(0); }
private static void EventSourceAddBuildStarted(object sender, CallbackArgs args) { BaseMock mock = (BaseMock)sender; mock["BuildStarted"] = args.GetParameter(0); }
private static void IncludeDebugInformationCallBack(object caller, CallbackArgs arguments) { BaseMock compiler = (BaseMock)caller; compiler["IncludeDebugInformation"] = arguments.GetParameter(0); }
private static void SourceFilesCallBack(object caller, CallbackArgs arguments) { BaseMock compiler = (BaseMock)caller; compiler["SourceFiles"] = arguments.GetParameter(0); }
public void MessageFormattingTest() { // Make sure that the registry key is no present so that we can set the verbosity. DeleteVerbosityKey(); using (OleServiceProvider provider = new OleServiceProvider()) { using (TaskProvider task = new TaskProvider(new ServiceProvider(provider))) { IVsHierarchy hierarchy = MockFactories.HierarchyForLogger(provider); IVsOutputWindowPane output = MockFactories.OutputPaneWithStringFunctions(); BaseMock mockOutput = (BaseMock)output; // Create the logger and make sure that it points to the verbosity IDELoggerProxy logger = new IDELoggerProxy(output, 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 and // build events. Assert.IsNotNull(mockSource["MessageRaised"]); BuildMessageEventHandler messageHandler = (BuildMessageEventHandler)mockSource["MessageRaised"]; Assert.IsNotNull(mockSource["BuildStarted"]); BuildStartedEventHandler buildStartedHandler = (BuildStartedEventHandler)mockSource["BuildStarted"]; Assert.IsNotNull(mockSource["BuildFinished"]); BuildFinishedEventHandler buildFinishedHandler = (BuildFinishedEventHandler)mockSource["BuildFinished"]; Assert.IsNotNull(mockSource["TaskStarted"]); TaskStartedEventHandler taskStartedHandler = (TaskStartedEventHandler)mockSource["TaskStarted"]; Assert.IsNotNull(mockSource["TaskFinished"]); TaskFinishedEventHandler taskFinishedHandler = (TaskFinishedEventHandler)mockSource["TaskFinished"]; // Set the verbosity to Diagnostic so that all the messages are written. logger.Verbosity = LoggerVerbosity.Diagnostic; // Create a message of the expected importance. BuildMessageEventArgs message = new BuildMessageEventArgs("message", "help", "sender", MessageImportance.Normal); messageHandler.Invoke(mockSource, message); // Add a second message with null text. message = new BuildMessageEventArgs(null, "help", "sender", MessageImportance.Normal); messageHandler.Invoke(mockSource, message); // Add another message with emty text. message = new BuildMessageEventArgs(string.Empty, "help", "sender", MessageImportance.Normal); messageHandler.Invoke(mockSource, message); System.Windows.Forms.Application.DoEvents(); string expected = "message" + Environment.NewLine; System.Text.StringBuilder builder = (System.Text.StringBuilder)mockOutput["StringBuilder"]; Assert.AreEqual(expected, builder.ToString(), false); // Clean up the text. output.Clear(); // Now verify the identation in case of start and end build events. string startText = "Test Started"; string messageText = "build message"; string endText = "Test Finished"; BuildStartedEventArgs startBuildArgs = new BuildStartedEventArgs(startText, "help"); buildStartedHandler.Invoke(mockSource, startBuildArgs); message = new BuildMessageEventArgs(messageText, "help", "sender", MessageImportance.Normal); messageHandler.Invoke(mockSource, message); BuildFinishedEventArgs finishBuildArgs = new BuildFinishedEventArgs(endText, "help", true); buildFinishedHandler.Invoke(mockSource, finishBuildArgs); System.Windows.Forms.Application.DoEvents(); // Get the text in the output pane. builder = (System.Text.StringBuilder)mockOutput["StringBuilder"]; expected = string.Format("{0}{1}{2}{1}{1}{3}{1}", startText, Environment.NewLine, messageText, endText); Assert.AreEqual(expected, builder.ToString(), false); // Clear the output and test the identation in case of start and end task. output.Clear(); TaskStartedEventArgs startTaskArgs = new TaskStartedEventArgs(startText, null, null, null, null); taskStartedHandler.Invoke(mockSource, startTaskArgs); message = new BuildMessageEventArgs(messageText, "help", "sender", MessageImportance.Normal); messageHandler.Invoke(mockSource, message); TaskFinishedEventArgs endTaskArgs = new TaskFinishedEventArgs(endText, null, null, null, null, true); taskFinishedHandler.Invoke(mockSource, endTaskArgs); System.Windows.Forms.Application.DoEvents(); // Verify the text in the output pane. expected = string.Format("{0}{1}\t{2}{1}{3}{1}", startText, Environment.NewLine, messageText, endText); builder = (System.Text.StringBuilder)mockOutput["StringBuilder"]; Assert.AreEqual(expected, builder.ToString(), false); } } }