public void RunTimesOutIfContextNotAvailable() { var logger = mocks.DynamicMock <ILogger>(); // Setup the first task var buildInfo1 = mocks.DynamicMock <BuildProgressInformation>(string.Empty, string.Empty); var result1 = mocks.Stub <IIntegrationResult>(); result1.Status = IntegrationStatus.Success; SetupResult.For(result1.Clone()).Return(result1); SetupResult.For(result1.BuildProgressInformation).Return(buildInfo1); var childTask11 = new SleepingTask { SleepPeriod = 2000, Result = IntegrationStatus.Success }; var childTask12 = new SleepingTask { SleepPeriod = 2000, Result = IntegrationStatus.Success }; var task1 = new SynchronisationTask { Logger = logger, Tasks = new ITask[] { childTask11, childTask12 }, TimeoutPeriod = 1 }; // Setup the first task var buildInfo2 = mocks.DynamicMock <BuildProgressInformation>(string.Empty, string.Empty); var result2 = mocks.Stub <IIntegrationResult>(); result2.Status = IntegrationStatus.Success; SetupResult.For(result2.Clone()).Return(result2); SetupResult.For(result2.BuildProgressInformation).Return(buildInfo2); var childTask21 = new SleepingTask { SleepPeriod = 2000, Result = IntegrationStatus.Success }; var childTask22 = new SleepingTask { SleepPeriod = 2000, Result = IntegrationStatus.Success }; var task2 = new SynchronisationTask { Logger = logger, Tasks = new ITask[] { childTask21, childTask22 }, TimeoutPeriod = 1 }; var event1 = new ManualResetEvent(false); var event2 = new ManualResetEvent(false); this.mocks.ReplayAll(); Assert.IsTrue(ThreadPool.QueueUserWorkItem(t1 => { task1.Run(result1); event1.Set(); })); Assert.IsTrue(ThreadPool.QueueUserWorkItem(t2 => { task2.Run(result2); event2.Set(); })); ManualResetEvent.WaitAll(new WaitHandle[] { event1, event2 }); this.mocks.VerifyAll(); // Only expect one of these to be successful if (result2.Status == IntegrationStatus.Success) { Assert.AreEqual(IntegrationStatus.Failure, result1.Status); } else { Assert.AreEqual(IntegrationStatus.Failure, result2.Status); } }
public void RunWithXsltArguments() { var working = Path.Combine(Path.GetTempPath(), "working"); var artefact = Path.Combine(Path.GetTempPath(), "artefact"); var label = "1.2.3.4"; var source = Path.Combine(working, "source.xml"); var stylesheet = Path.Combine(working, "stylesheet.xsl"); var output = Path.Combine(working, "output.xml"); // Mock the file system var fileSystem = mocks.StrictMock <IFileSystem>(); Expect.Call(fileSystem.OpenInputStream(source)).Return(new MemoryStream()); Expect.Call(fileSystem.OpenOutputStream(output)).Return(new MemoryStream()); // Mock the transformer var transformer = mocks.StrictMock <ITransformer>(); Expect.Call(transformer.Transform(null, null, null)). IgnoreArguments().Constraints( Rhino.Mocks.Constraints.Is.Equal(""), Rhino.Mocks.Constraints.Is.Equal(stylesheet), Rhino.Mocks.Constraints.Is.TypeOf(typeof(Hashtable)) && Rhino.Mocks.Constraints.List.Count(Rhino.Mocks.Constraints.Is.Equal(1)) && Rhino.Mocks.Constraints.List.Element <string>("Test", Rhino.Mocks.Constraints.Is.Equal("SomeValue")) ). Return(""); // Initialise the task var task = new XslTransformationTask(transformer, fileSystem) { XMLFile = source, XSLFile = stylesheet, OutputFile = output, XsltArgs = new NameValuePair[1] { new NameValuePair() { Name = "Test", Value = "SomeValue" } } }; // Mock the result var result = mocks.StrictMock <IIntegrationResult>(); Expect.Call(result.Status).PropertyBehavior(); var buildProgress = mocks.StrictMock <BuildProgressInformation>(artefact, "Project1"); SetupResult.For(result.BuildProgressInformation) .Return(buildProgress); SetupResult.For(result.WorkingDirectory).Return(working); SetupResult.For(result.ArtifactDirectory).Return(artefact); SetupResult.For(result.Label).Return(label); Expect.Call(() => { buildProgress.SignalStartRunTask("Transforming"); }); // Run the test mocks.ReplayAll(); result.Status = IntegrationStatus.Unknown; task.Run(result); // Check the results mocks.VerifyAll(); }
public void UpdateIssueDataForResourceWithNewDateDataTestWithCache() { var fileSource = new Source { Lines = new[] { "line1", "line2", "line3", "line4" } }; var newResource = new Resource { Date = DateTime.Now, Key = "resource" }; var source1 = new SourceCoverage(); source1.SetLineCoverageData("1=0;2=3;3=3"); source1.SetBranchCoverageData("1=0;2=3;3=3", "1=0;2=3;3=3"); this.service.Expect( mp => mp.GetResourcesData(Arg <ISonarConfiguration> .Is.Anything, Arg <string> .Is.Anything)) .Return(new List <Resource> { newResource }); this.service.Expect( mp => mp.GetSourceForFileResource(Arg <ISonarConfiguration> .Is.Anything, Arg <string> .Is.Anything)) .Return(fileSource) .Repeat.Once(); this.service.Expect( mp => mp.GetIssuesInResource(Arg <ISonarConfiguration> .Is.Anything, Arg <string> .Is.Anything)) .Return(new List <Issue> { new Issue { Severity = Severity.CRITICAL, Line = 1 } }) .Repeat.Once(); this.service.Expect( mp => mp.GetCoverageInResource(Arg <ISonarConfiguration> .Is.Anything, Arg <string> .Is.Anything)) .Return(source1) .Repeat.Once(); this.analysisPlugin.Expect( mp => mp.GetResourceKey(Arg <VsProjectItem> .Is.Anything, Arg <string> .Is.Anything, Arg <bool> .Is.Anything)) .Return("resource"); var data = new ExtensionDataModel(this.service, this.vshelper, null, null); data.AssociatedProject = new Resource { Key = "sonar.com:common" }; var localAnalyser = this.mocks.Stub <ISonarLocalAnalyser>(); data.LocalAnalyserModule = localAnalyser; using (this.mocks.Record()) { SetupResult.For(localAnalyser.GetResourceKey(Arg <VsProjectItem> .Is.Anything, Arg <Resource> .Is.Anything, Arg <ISonarConfiguration> .Is.Anything, Arg <bool> .Is.Equal(true))).Return("Key1"); SetupResult.For(localAnalyser.GetResourceKey(Arg <VsProjectItem> .Is.Anything, Arg <Resource> .Is.Anything, Arg <ISonarConfiguration> .Is.Anything, Arg <bool> .Is.Equal(false))).Return("Key2"); } data.RefreshDataForResource("resource"); Assert.AreEqual(1, data.GetIssuesInEditor("line1\r\nline2\r\nline3\r\nline4\r\n").Count); }
public void RunAllowsTasksInSeparateContexts() { var logger = mocks.DynamicMock <ILogger>(); // Setup the first task var buildInfo1 = mocks.DynamicMock <BuildProgressInformation>(string.Empty, string.Empty); var result1 = mocks.Stub <IIntegrationResult>(); result1.Status = IntegrationStatus.Success; SetupResult.For(result1.Clone()).Return(result1); SetupResult.For(result1.BuildProgressInformation).Return(buildInfo1); var childTask11 = new SleepingTask { SleepPeriod = 1000, Result = IntegrationStatus.Success }; var childTask12 = new SleepingTask { SleepPeriod = 1000, Result = IntegrationStatus.Success }; var task1 = new SynchronisationTask { Logger = logger, Tasks = new ITask[] { childTask11, childTask12 }, ContextName = "customContext1" }; // Setup the first task var buildInfo2 = mocks.DynamicMock <BuildProgressInformation>(string.Empty, string.Empty); var result2 = mocks.Stub <IIntegrationResult>(); result2.Status = IntegrationStatus.Success; SetupResult.For(result2.Clone()).Return(result2); SetupResult.For(result2.BuildProgressInformation).Return(buildInfo2); var childTask21 = new SleepingTask { SleepPeriod = 1000, Result = IntegrationStatus.Success }; var childTask22 = new SleepingTask { SleepPeriod = 1000, Result = IntegrationStatus.Success }; var task2 = new SynchronisationTask { Logger = logger, Tasks = new ITask[] { childTask21, childTask22 }, ContextName = "customContext2" }; var event1 = new ManualResetEvent(false); var event2 = new ManualResetEvent(false); this.mocks.ReplayAll(); Assert.IsTrue(ThreadPool.QueueUserWorkItem(t1 => { task1.Run(result1); event1.Set(); })); Assert.IsTrue(ThreadPool.QueueUserWorkItem(t2 => { task2.Run(result2); event2.Set(); })); ManualResetEvent.WaitAll(new WaitHandle[] { event1, event2 }); this.mocks.VerifyAll(); Assert.AreEqual(IntegrationStatus.Success, result1.Status); Assert.AreEqual(IntegrationStatus.Success, result2.Status); }
public static void SetHttpMethodResult(this HttpRequestBase request, string httpMethod) { SetupResult.For(request.HttpMethod).Return(httpMethod); }
public void ExecuteGeneratesList() { var package1 = new PackageDetails { BuildLabel = "label1", DateTime = new DateTime(2010, 1, 2, 3, 4, 5), FileName = "somewhere\\thefile.type", Name = "theName", NumberOfFiles = 2, Size = 1 }; var package2 = new PackageDetails { BuildLabel = "label2", DateTime = new DateTime(2010, 10, 9, 8, 7, 6), FileName = "anotherfile.txt", Name = "secondName", NumberOfFiles = 5, Size = 9876 }; var package3 = new PackageDetails { BuildLabel = "label3", DateTime = new DateTime(2010, 1, 1, 2, 3, 5), FileName = "anotherfile.txt", Name = "secondName", NumberOfFiles = 5, Size = 1234567890 }; var packages = new PackageDetails[] { package1, package2, package3 }; var projectName = "Test Project"; var farmService = this.mocks.StrictMock <IFarmService>(); var viewGenerator = this.mocks.StrictMock <IVelocityViewGenerator>(); var cruiseRequest = this.mocks.StrictMock <ICruiseRequest>(); var projectSpec = this.mocks.StrictMock <IProjectSpecifier>(); SetupResult.For(cruiseRequest.ProjectName).Return(projectName); SetupResult.For(cruiseRequest.ProjectSpecifier).Return(projectSpec); SetupResult.For(cruiseRequest.RetrieveSessionToken()).Return(null); SetupResult.For(farmService.RetrievePackageList(projectSpec, null)).Return(packages); Expect.Call(viewGenerator.GenerateView(null, null)) .Callback <string, Hashtable>((n, ht) => { Assert.AreEqual("PackageList.vm", n); Assert.IsNotNull(ht); Assert.IsTrue(ht.ContainsKey("projectName")); Assert.AreEqual(projectName, ht["projectName"]); Assert.IsTrue(ht.ContainsKey("packages")); Assert.IsInstanceOf <List <PackageListAction.PackageDisplay> >(ht["packages"]); return(true); }) .Return(new HtmlFragmentResponse("from nVelocity")); this.mocks.ReplayAll(); var plugin = new PackageListAction(viewGenerator, farmService); var response = plugin.Execute(cruiseRequest); this.mocks.VerifyAll(); Assert.IsInstanceOf <HtmlFragmentResponse>(response); var actual = response as HtmlFragmentResponse; var expected = "from nVelocity"; Assert.AreEqual(expected, actual.ResponseFragment); }
/// <summary> /// Initialises the server. /// </summary> /// <param name="mocks">The mocks repository.</param> /// <param name="buildName">Name of the build.</param> /// <param name="buildLog">The build log.</param> /// <returns>The initialised server.</returns> private static CruiseServer InitialiseServer(MockRepository mocks, string buildName, string buildLog) { // Add some projects var projects = new ProjectList(); var project = new Project { Name = testProjectName }; projects.Add(project); // Mock the configuration var configuration = mocks.StrictMock <IConfiguration>(); SetupResult.For(configuration.Projects) .Return(projects); SetupResult.For(configuration.SecurityManager) .Return(new NullSecurityManager()); // Mock the configuration service var configService = mocks.StrictMock <IConfigurationService>(); SetupResult.For(configService.Load()) .Return(configuration); Expect.Call(() => { configService.AddConfigurationUpdateHandler(null); }) .IgnoreArguments(); // Mock the integration repostory var repository = mocks.StrictMock <IIntegrationRepository>(); SetupResult.For(repository.GetBuildLog(buildName)) .Return(buildLog); // Mock the project integrator var projectIntegrator = mocks.StrictMock <IProjectIntegrator>(); SetupResult.For(projectIntegrator.Project) .Return(project); SetupResult.For(projectIntegrator.IntegrationRepository) .Return(repository); // Mock the queue manager var queueManager = mocks.StrictMock <IQueueManager>(); Expect.Call(() => { queueManager.AssociateIntegrationEvents(null, null); }) .IgnoreArguments(); SetupResult.For(queueManager.GetIntegrator(testProjectName)) .Return(projectIntegrator); // Mock the queue manager factory var queueManagerFactory = mocks.StrictMock <IQueueManagerFactory>(); SetupResult.For(queueManagerFactory.Create(null, configuration, null)) .Return(queueManager); IntegrationQueueManagerFactory.OverrideFactory(queueManagerFactory); // Mock the execution environment var execEnviron = mocks.StrictMock <IExecutionEnvironment>(); SetupResult.For(execEnviron.GetDefaultProgramDataFolder(ApplicationType.Server)) .Return(string.Empty); // Initialise the server mocks.ReplayAll(); var server = new CruiseServer( configService, null, null, null, null, execEnviron, null); return(server); }
// Helper class to provide a common set of tests for constructor-args based // multi-mocks testing. Exercises a mocked StringWriter (which should also be an IDataErrorInfo) // constructed with a mocked IFormatProvider. The test checks the semantics // of the mocked StringWriter to compare it with the expected semantics. private static void CommonConstructorArgsTest(MockRepository mocks, StringBuilder stringBuilder, IFormatProvider formatProvider, StringWriter mockedWriter, MockType mockType) { string stringToWrite = "The original string"; string stringToWriteLine = "Extra bit"; IDataErrorInfo errorInfo = mockedWriter as IDataErrorInfo; Assert.NotNull(errorInfo); // Configure expectations for mocked writer SetupResult.For(mockedWriter.FormatProvider).CallOriginalMethod(OriginalCallOptions.CreateExpectation); mockedWriter.Write((string)null); LastCall.IgnoreArguments().CallOriginalMethod(OriginalCallOptions.CreateExpectation); mockedWriter.Flush(); LastCall.Repeat.Any().CallOriginalMethod(OriginalCallOptions.CreateExpectation); mockedWriter.Close(); // Configure expectations for object through interface Expect.Call(errorInfo.Error).Return(null).Repeat.Once(); Expect.Call(errorInfo.Error).Return("error!!!").Repeat.Once(); mocks.ReplayAll(); // Ensure that arguments arrived okay // Is the format provider correct Assert.Same(formatProvider, mockedWriter.FormatProvider); // Does writing to the writer forward to our stringbuilder from the constructor? mockedWriter.Write(stringToWrite); mockedWriter.Flush(); // Let's see what mode our mock is running in. // We have not configured WriteLine at all, so: // a) if we're running as a strict mock, it'll fail // b) if we're running as a dynamic mock, it'll no-op // c) if we're running as a partial mock, it'll work try { mockedWriter.WriteLine(stringToWriteLine); } catch (ExpectationViolationException) { // We're operating strictly. Assert.Equal(MockType.Strict, mockType); } string expectedStringBuilderContents = null; switch (mockType) { case MockType.Dynamic: case MockType.Strict: // The writeline won't have done anything expectedStringBuilderContents = stringToWrite; break; case MockType.Partial: // The writeline will have worked expectedStringBuilderContents = stringToWrite + stringToWriteLine + Environment.NewLine; break; } Assert.Equal(expectedStringBuilderContents, stringBuilder.ToString()); // Satisfy expectations. mockedWriter.Close(); Assert.Null(errorInfo.Error); Assert.Equal("error!!!", errorInfo.Error); if (MockType.Strict != mockType) { mocks.VerifyAll(); } }
public void FormatWritesTheArchivedReport() { IReportWriter reportWriter = Mocks.StrictMock <IReportWriter>(); IReportContainer reportContainer = Mocks.StrictMock <IReportContainer>(); IReportFormatter htmlReportFormatter = Mocks.StrictMock <IReportFormatter>(); IProgressMonitor progressMonitor = NullProgressMonitor.CreateInstance(); var reportFormatterOptions = new ReportFormatterOptions(); string reportPath = SpecialPathPolicy.For <MHtmlReportFormatterTest>().CreateTempFileWithUniqueName().FullName; using (Stream tempFileStream = File.OpenWrite(reportPath)) { using (Mocks.Record()) { SetupResult.For(reportWriter.ReportContainer).Return(reportContainer); SetupResult.For(reportWriter.Report).Return(new Report()); Expect.Call(reportContainer.EncodeFileName(null)) .Repeat.Any() .IgnoreArguments() .Do((Gallio.Common.GallioFunc <string, string>) delegate(string value) { return(value); }); SetupResult.For(reportContainer.ReportName).Return("Foo"); Expect.Call(reportContainer.OpenWrite("Foo.mht", MimeTypes.MHtml, new UTF8Encoding(false))) .Return(tempFileStream); reportWriter.AddReportDocumentPath("Foo.mht"); Expect.Call(delegate { htmlReportFormatter.Format(null, null, null); }) .Constraints(Is.NotNull(), Is.Same(reportFormatterOptions), Is.NotNull()) .Do((FormatDelegate) delegate(IReportWriter innerReportWriter, ReportFormatterOptions innerFormatterOptions, IProgressMonitor innerProgressMonitor) { using (StreamWriter contentWriter = new StreamWriter(innerReportWriter.ReportContainer.OpenWrite("Foo.html", MimeTypes.Html, Encoding.UTF8))) contentWriter.Write("<html><body>Some HTML</body></html>"); using (StreamWriter contentWriter = new StreamWriter(innerReportWriter.ReportContainer.OpenWrite( innerReportWriter.ReportContainer.EncodeFileName("Foo\\Attachment 1%.txt"), MimeTypes.PlainText, Encoding.UTF8))) contentWriter.Write("An attachment."); using (StreamWriter contentWriter = new StreamWriter(innerReportWriter.ReportContainer.OpenWrite("Foo.css", null, null))) contentWriter.Write("#Some CSS."); }); } using (Mocks.Playback()) { MHtmlReportFormatter formatter = new MHtmlReportFormatter(htmlReportFormatter); formatter.Format(reportWriter, reportFormatterOptions, progressMonitor); string reportContents = File.ReadAllText(reportPath); TestLog.AttachPlainText("MHTML Report", reportContents); Assert.Contains(reportContents, "MIME-Version: 1.0"); Assert.Contains(reportContents, "Content-Type: multipart/related; type=\"text/html\"; boundary="); Assert.Contains(reportContents, "This is a multi-part message in MIME format."); Assert.Contains(reportContents, "text/html"); Assert.Contains(reportContents, "Content-Location: file:///Foo.html"); Assert.Contains(reportContents, Convert.ToBase64String(Encoding.UTF8.GetBytes("<html><body>Some HTML</body></html>"), Base64FormattingOptions.InsertLineBreaks)); Assert.Contains(reportContents, "text/plain"); Assert.Contains(reportContents, "Content-Location: file:///Foo/Attachment_1%25.txt"); Assert.Contains(reportContents, Convert.ToBase64String(Encoding.UTF8.GetBytes("An attachment."), Base64FormattingOptions.InsertLineBreaks)); Assert.Contains(reportContents, "text/css"); Assert.Contains(reportContents, "Content-Location: file:///Foo.css"); Assert.Contains(reportContents, Convert.ToBase64String(Encoding.UTF8.GetBytes("#Some CSS."), Base64FormattingOptions.InsertLineBreaks)); File.Delete(reportPath); } } }