public void AttachmentInformationShouldBeWrittenToConsoleIfAttachmentsArePresent()
        {
            var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance);

            loggerEvents.EnableEvents();
            var parameters = new Dictionary <string, string>();

            parameters.Add("verbosity", "normal");
            this.consoleLogger.Initialize(loggerEvents, parameters);

            var attachmentSet     = new AttachmentSet(new Uri("test://uri"), "myattachmentset");
            var uriDataAttachment = new UriDataAttachment(new Uri("file://server/filename.ext"), "description");

            attachmentSet.Attachments.Add(uriDataAttachment);
            var uriDataAttachment1 = new UriDataAttachment(new Uri("file://server/filename1.ext"), "description");

            attachmentSet.Attachments.Add(uriDataAttachment1);
            var attachmentSetList = new List <AttachmentSet>
            {
                attachmentSet
            };

            loggerEvents.CompleteTestRun(null, false, false, null, new Collection <AttachmentSet>(attachmentSetList), new TimeSpan(1, 0, 0, 0));

            this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.AttachmentOutputFormat, uriDataAttachment.Uri.LocalPath), OutputLevel.Information), Times.Once());
            this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.AttachmentOutputFormat, uriDataAttachment1.Uri.LocalPath), OutputLevel.Information), Times.Once());
        }
Exemple #2
0
        public Task <ICollection <AttachmentSet> > ProcessAttachmentSetsAsync(XmlElement configurationElement, ICollection <AttachmentSet> attachments, IProgress <int> progressReporter, IMessageLogger logger, CancellationToken cancellationToken)
        {
            string        finalFileName = configurationElement.FirstChild.InnerText;
            StringBuilder stringBuilder = new StringBuilder();
            string        finalFolder   = null;

            foreach (var attachmentSet in attachments)
            {
                foreach (var attachment in attachmentSet.Attachments.OrderBy(f => f.Uri.AbsolutePath))
                {
                    if (finalFolder is null)
                    {
                        finalFolder = Path.GetDirectoryName(attachment.Uri.AbsolutePath);
                    }

                    stringBuilder.AppendLine(File.ReadAllText(attachment.Uri.AbsolutePath).Trim());
                }
            }

            File.WriteAllText(Path.Combine(finalFolder, finalFileName), stringBuilder.ToString());

            List <AttachmentSet> mergedAttachment = new List <AttachmentSet>();
            var mergedAttachmentSet = new AttachmentSet(new Uri("my://sample/datacollector"), "SampleDataCollector");

            mergedAttachmentSet.Attachments.Add(UriDataAttachment.CreateFrom(Path.Combine(finalFolder, finalFileName), string.Empty));
            mergedAttachment.Add(mergedAttachmentSet);

            return(Task.FromResult((ICollection <AttachmentSet>) new Collection <AttachmentSet>(mergedAttachment)));
        }
Exemple #3
0
        /// <summary>
        /// Convert parameter unitTestResult to testResult
        /// </summary>
        /// <param name="testCase"> The test Case.  </param>
        /// <param name="startTime"> The start Time.  </param>
        /// <param name="endTime"> The end Time.  </param>
        /// <param name="currentSettings">Current MSTest settings.</param>
        /// <returns> The <see cref="TestResult"/>. </returns>
        internal TestResult ToTestResult(TestCase testCase, DateTimeOffset startTime, DateTimeOffset endTime, MSTestSettings currentSettings)
        {
            Debug.Assert(testCase != null, "testCase");

            var testResult = new TestResult(testCase)
            {
                DisplayName     = this.DisplayName,
                Duration        = this.Duration,
                ErrorMessage    = this.ErrorMessage,
                ErrorStackTrace = this.ErrorStackTrace,
                Outcome         = UnitTestOutcomeHelper.ToTestOutcome(this.Outcome, currentSettings),
                StartTime       = startTime,
                EndTime         = endTime
            };

            testResult.SetPropertyValue <Guid>(Constants.ExecutionIdProperty, this.ExecutionId);
            testResult.SetPropertyValue <Guid>(Constants.ParentExecIdProperty, this.ParentExecId);
            testResult.SetPropertyValue <int>(Constants.InnerResultsCountProperty, this.InnerResultsCount);

            if (!string.IsNullOrEmpty(this.StandardOut))
            {
                TestResultMessage message = new TestResultMessage(TestResultMessage.StandardOutCategory, this.StandardOut);
                testResult.Messages.Add(message);
            }

            if (!string.IsNullOrEmpty(this.StandardError))
            {
                TestResultMessage message = new TestResultMessage(TestResultMessage.StandardErrorCategory, this.StandardError);
                testResult.Messages.Add(message);
            }

            if (!string.IsNullOrEmpty(this.DebugTrace))
            {
                string            debugTraceMessagesinStdOut = string.Format(CultureInfo.InvariantCulture, "\n\n{0}\n{1}", Resource.DebugTraceBanner, this.DebugTrace);
                TestResultMessage debugTraceMessage          = new TestResultMessage(TestResultMessage.StandardOutCategory, debugTraceMessagesinStdOut);
                testResult.Messages.Add(debugTraceMessage);
            }

            if (!string.IsNullOrEmpty(this.TestContextMessages))
            {
                string            testContextMessagesInStdOut = string.Format(CultureInfo.InvariantCulture, "\n\n{0}\n{1}", Resource.TestContextMessageBanner, this.TestContextMessages);
                TestResultMessage testContextMessage          = new TestResultMessage(TestResultMessage.StandardOutCategory, testContextMessagesInStdOut);
                testResult.Messages.Add(testContextMessage);
            }

            if (this.ResultFiles != null && this.ResultFiles.Count > 0)
            {
                AttachmentSet attachmentSet = new AttachmentSet(Constants.ExecutorUri, Resource.AttachmentSetDisplayName);
                foreach (var resultFile in this.ResultFiles)
                {
                    string            pathToResultFile = PlatformServiceProvider.Instance.FileOperations.GetFullFilePath(resultFile);
                    UriDataAttachment attachment       = new UriDataAttachment(new Uri(pathToResultFile), resultFile);
                    attachmentSet.Attachments.Add(attachment);
                }

                testResult.Attachments.Add(attachmentSet);
            }

            return(testResult);
        }
        public void TestRunCompleteHandlerShouldGetFaultyTestRunIfTestRunAborted()
        {
            // Initialize
            var attachmentSet     = new AttachmentSet(new Uri("test://uri"), "Blame");
            var uriDataAttachment = new UriDataAttachment(new Uri("C:/folder1/sequence.xml"), "description");

            attachmentSet.Attachments.Add(uriDataAttachment);
            var attachmentSetList = new List <AttachmentSet> {
                attachmentSet
            };

            // Initialize Blame Logger
            this.blameLogger.Initialize(this.events.Object, null);

            var testCaseList =
                new List <TestCase>
            {
                new TestCase("ABC.UnitTestMethod1", new Uri("test://uri"), "C://test/filepath"),
                new TestCase("ABC.UnitTestMethod2", new Uri("test://uri"), "C://test/filepath")
            };

            // Setup and Raise event
            this.mockBlameReaderWriter.Setup(x => x.ReadTestSequence(It.IsAny <string>())).Returns(testCaseList);
            this.testRunRequest.Raise(
                m => m.OnRunCompletion += null,
                new TestRunCompleteEventArgs(stats: null, isCanceled: false, isAborted: true, error: null, attachmentSets: new Collection <AttachmentSet>(attachmentSetList), elapsedTime: new TimeSpan(1, 0, 0, 0)));

            // Verify Call
            this.mockBlameReaderWriter.Verify(x => x.ReadTestSequence(It.IsAny <string>()), Times.Once);
        }
 private static void VerifyAttachment(UriDataAttachment attachment, string expectedName, string expectedDescription)
 {
     Assert.Multiple(() =>
     {
         Assert.That(attachment.Uri.OriginalString, Does.EndWith(expectedName));
         Assert.That(attachment.Description, Is.EqualTo(expectedDescription));
     });
 }
        private AttachmentSet GetAttachmentSet()
        {
            var attachmentSet     = new AttachmentSet(new Uri("test://uri"), "Blame");
            var uriDataAttachment = new UriDataAttachment(new Uri("C:/folder1/sequence.xml"), "description");

            attachmentSet.Attachments.Add(uriDataAttachment);

            return(attachmentSet);
        }
Exemple #7
0
        // Returns a list of collector entry
        private static CollectorDataEntry ToCollectorEntry(ObjectModel.AttachmentSet attachmentSet, Guid testResultExecutionId, TestRun testRun, string trxFileDirectory)
        {
            string runDirectoryName = Path.Combine(trxFileDirectory, testRun.RunConfiguration.RunDeploymentRootDirectory);
            string inDirectory      = Path.Combine(runDirectoryName, "In");

            string targetDirectory = inDirectory;

            if (!testResultExecutionId.Equals(Guid.Empty))
            {
                targetDirectory = Path.Combine(inDirectory, testResultExecutionId.ToString());
            }

            targetDirectory = Path.Combine(targetDirectory, Environment.MachineName);

            if (!Directory.Exists(targetDirectory))
            {
                Directory.CreateDirectory(targetDirectory);
            }

            List <IDataAttachment> uriDataAttachments = new List <IDataAttachment>();

            foreach (ObjectModel.UriDataAttachment uriDataAttachment in attachmentSet.Attachments)
            {
                if (ObjectModel.EqtTrace.IsVerboseEnabled)
                {
                    ObjectModel.EqtTrace.Verbose("TrxLogger: ToCollectorEntry: Got attachment " + uriDataAttachment.Uri + " with description " + uriDataAttachment.Description);
                }

                string sourceFile = uriDataAttachment.Uri.LocalPath;
                Debug.Assert(Path.IsPathRooted(sourceFile), "Source file is not rooted");

                // copy the source file to the target location
                string targetFileName = FileHelper.GetNextIterationFileName(targetDirectory, Path.GetFileName(sourceFile), false);
                CopyFile(sourceFile, targetFileName);

                // Add the source file name to the collector files list.
                // (Trx viewer automatically adds In\ to the collected file.
                string            fileName       = Path.Combine(Environment.MachineName, Path.GetFileName(sourceFile));
                Uri               sourceFileUri  = new Uri(fileName, UriKind.Relative);
                UriDataAttachment dataAttachment = new UriDataAttachment(uriDataAttachment.Description, sourceFileUri);

                uriDataAttachments.Add(dataAttachment);
            }

            return(new CollectorDataEntry(
                       attachmentSet.Uri,
                       attachmentSet.DisplayName,
                       Environment.MachineName,
                       Environment.MachineName,
                       false,
                       uriDataAttachments));
        }
        private static StringBuilder GetFileAsString(UriDataAttachment vstsAttachment)
        {
            var sb = new StringBuilder();

            using (var sr = new StreamReader(vstsAttachment.Uri.LocalPath))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    sb.AppendLine(line);
                }
            }
            return(sb);
        }
        public async Task <ICollection <AttachmentSet> > ProcessAttachmentSetsAsync(ICollection <AttachmentSet> attachments, IProgress <int> progressReporter, IMessageLogger logger, CancellationToken cancellationToken)
        {
            if (attachments != null && attachments.Any())
            {
                var coverageReportFilePaths = new List <string>();
                var coverageOtherFilePaths  = new List <string>();

                foreach (var attachmentSet in attachments)
                {
                    foreach (var attachment in attachmentSet.Attachments)
                    {
                        if (attachment.Uri.LocalPath.EndsWith(CoverageFileExtension, StringComparison.OrdinalIgnoreCase))
                        {
                            coverageReportFilePaths.Add(attachment.Uri.LocalPath);
                        }
                        else
                        {
                            coverageOtherFilePaths.Add(attachment.Uri.LocalPath);
                        }
                    }
                }

                if (coverageReportFilePaths.Count > 1)
                {
                    var mergedCoverageReportFilePath = await this.MergeCodeCoverageFilesAsync(coverageReportFilePaths, progressReporter, cancellationToken).ConfigureAwait(false);

                    if (!string.IsNullOrEmpty(mergedCoverageReportFilePath))
                    {
                        var resultAttachmentSet = new AttachmentSet(CodeCoverageDataCollectorUri, CoverageFriendlyName);
                        resultAttachmentSet.Attachments.Add(UriDataAttachment.CreateFrom(mergedCoverageReportFilePath, CoverageFriendlyName));

                        foreach (var coverageOtherFilePath in coverageOtherFilePaths)
                        {
                            resultAttachmentSet.Attachments.Add(UriDataAttachment.CreateFrom(coverageOtherFilePath, string.Empty));
                        }

                        return(new Collection <AttachmentSet> {
                            resultAttachmentSet
                        });
                    }
                }

                return(attachments);
            }

            return(new Collection <AttachmentSet>());
        }
        private static Attachment GetBinaryAttachment(UriDataAttachment vstsAttachment, string fileEx)
        {
            var mem = new MemoryStream();
            var f   = new FileStream(vstsAttachment.Uri.LocalPath, FileMode.Open, FileAccess.Read);

            mem.SetLength(f.Length);

            f.Read(mem.GetBuffer(), 0, (int)f.Length - 1);

            var mime = MimeTypes.GetMimeTypeByExtension(fileEx) ?? MimeTypes.Binary;

            var binaryAttachment = new BinaryAttachment(vstsAttachment.Description, mime, mem.ToArray());

            f.Close();
            mem.Close();

            return(binaryAttachment);
        }
Exemple #11
0
        public void ShouldPublishAttachedFiles()
        {
            // Given
            var attachment    = new UriDataAttachment(new Uri("file:///Images/My.jpg"), "My image");
            var testResult    = CreateTestResult();
            var attachmentSet = new AttachmentSet(new Uri("file:///abc"), "attachments");

            attachmentSet.Attachments.Add(attachment);
            testResult.Result.Attachments.Add(attachmentSet);
            _idGenerator.Setup(i => i.NewId()).Returns("id");

            // When
            _events.OnTestResult(testResult);
            _events.OnTestRunComplete();

            // Then
            _attachments.Verify(i => i.SendAttachment("test1", attachment, It.IsAny <ITeamCityTestWriter>()));
        }
Exemple #12
0
        public void AttachmentInformationShouldBeWrittenToConsoleIfAttachmentsArePresent()
        {
            var attachmentSet     = new AttachmentSet(new Uri("test://uri"), "myattachmentset");
            var uriDataAttachment = new UriDataAttachment(new Uri("file://server/filename.ext"), "description");

            attachmentSet.Attachments.Add(uriDataAttachment);
            var uriDataAttachment1 = new UriDataAttachment(new Uri("file://server/filename1.ext"), "description");

            attachmentSet.Attachments.Add(uriDataAttachment1);
            var attachmentSetList = new List <AttachmentSet>();

            attachmentSetList.Add(attachmentSet);
            var testRunCompleteEventArgs = new TestRunCompleteEventArgs(null, false, false, null, new Collection <AttachmentSet>(attachmentSetList), new TimeSpan(1, 0, 0, 0));

            // Raise an event on mock object raised to register test case count and mark Outcome as Outcome.Failed
            this.testRunRequest.Raise(m => m.OnRunCompletion += null, testRunCompleteEventArgs);

            this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.AttachmentOutputFormat, uriDataAttachment.Uri.LocalPath), OutputLevel.Information), Times.Once());
            this.mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.AttachmentOutputFormat, uriDataAttachment1.Uri.LocalPath), OutputLevel.Information), Times.Once());
        }
Exemple #13
0
 public AttachmentDrop(UriDataAttachment uriDataAttachment)
 {
     _uriDataAttachment = uriDataAttachment;
 }
 private static BinaryAttachment GetImageAttachment(UriDataAttachment vstsAttachment)
 {
     var image = Image.FromFile(vstsAttachment.Uri.LocalPath);
         
     return Attachment.CreateImageAttachment(vstsAttachment.Description, image);
 }
        private static TextAttachment GetHtmlAttachment(UriDataAttachment vstsAttachment)
        {
            var sb = GetFileAsString(vstsAttachment);

            return(Attachment.CreateHtmlAttachment(vstsAttachment.Description, sb.ToString()));
        }
        private static BinaryAttachment GetImageAttachment(UriDataAttachment vstsAttachment)
        {
            var image = Image.FromFile(vstsAttachment.Uri.LocalPath);

            return(Attachment.CreateImageAttachment(vstsAttachment.Description, image));
        }
        /// <summary>
        /// Add a new file transfer (either copy/move) request.
        /// </summary>
        /// <param name="fileTransferInfo">
        /// The file Transfer Info.
        /// </param>
        /// <param name="sendFileCompletedCallback">
        /// The send File Completed Callback.
        /// </param>
        /// <param name="uri">
        /// The uri.
        /// </param>
        /// <param name="friendlyName">
        /// The friendly Name.
        /// </param>
        private void AddNewFileTransfer(FileTransferInformation fileTransferInfo, AsyncCompletedEventHandler sendFileCompletedCallback, Uri uri, string friendlyName)
        {
            var context = fileTransferInfo.Context;

            Debug.Assert(
                context != null,
                "DataCollectionManager.AddNewFileTransfer: FileDataHeaderMessage with null context.");

            var testCaseId = fileTransferInfo.Context.HasTestCase
                                 ? fileTransferInfo.Context.TestExecId.Id.ToString()
                                 : string.Empty;

            var directoryPath = Path.Combine(
                this.SessionOutputDirectory,
                testCaseId);
            var localFilePath = Path.Combine(directoryPath, Path.GetFileName(fileTransferInfo.FileName));

            var task = Task.Factory.StartNew(
                () =>
            {
                Validate(fileTransferInfo, localFilePath);

                if (this.cancellationTokenSource.Token.IsCancellationRequested)
                {
                    this.cancellationTokenSource.Token.ThrowIfCancellationRequested();
                }

                try
                {
                    if (fileTransferInfo.PerformCleanup)
                    {
                        if (EqtTrace.IsInfoEnabled)
                        {
                            EqtTrace.Info("DataCollectionAttachmentManager.AddNewFileTransfer : Moving file {0} to {1}", fileTransferInfo.FileName, localFilePath);
                        }

                        this.fileHelper.MoveFile(fileTransferInfo.FileName, localFilePath);

                        if (EqtTrace.IsInfoEnabled)
                        {
                            EqtTrace.Info("DataCollectionAttachmentManager.AddNewFileTransfer : Moved file {0} to {1}", fileTransferInfo.FileName, localFilePath);
                        }
                    }
                    else
                    {
                        if (EqtTrace.IsInfoEnabled)
                        {
                            EqtTrace.Info("DataCollectionAttachmentManager.AddNewFileTransfer : Copying file {0} to {1}", fileTransferInfo.FileName, localFilePath);
                        }

                        this.fileHelper.CopyFile(fileTransferInfo.FileName, localFilePath);

                        if (EqtTrace.IsInfoEnabled)
                        {
                            EqtTrace.Info("DataCollectionAttachmentManager.AddNewFileTransfer : Copied file {0} to {1}", fileTransferInfo.FileName, localFilePath);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.LogError(
                        ex.ToString(),
                        uri,
                        friendlyName,
                        Guid.Parse(testCaseId));

                    throw;
                }
            },
                this.cancellationTokenSource.Token);

            var continuationTask = task.ContinueWith(
                (t) =>
            {
                try
                {
                    if (t.Exception == null)
                    {
                        lock (attachmentTaskLock)
                        {
                            this.AttachmentSets[fileTransferInfo.Context][uri].Attachments.Add(UriDataAttachment.CreateFrom(localFilePath, fileTransferInfo.Description));
                        }
                    }

                    sendFileCompletedCallback?.Invoke(this, new AsyncCompletedEventArgs(t.Exception, false, fileTransferInfo.UserToken));
                }
                catch (Exception e)
                {
                    if (EqtTrace.IsErrorEnabled)
                    {
                        EqtTrace.Error(
                            "DataCollectionAttachmentManager.TriggerCallBack: Error occurred while raising the file transfer completed callback for {0}. Error: {1}",
                            localFilePath,
                            e.ToString());
                    }
                }
            },
                this.cancellationTokenSource.Token);

            this.attachmentTasks[fileTransferInfo.Context].Add(continuationTask);
        }
        private static TextAttachment GetHtmlAttachment(UriDataAttachment vstsAttachment)
        {
            var sb = GetFileAsString(vstsAttachment);

            return Attachment.CreateHtmlAttachment(vstsAttachment.Description, sb.ToString());
        }
        private static Attachment GetBinaryAttachment(UriDataAttachment vstsAttachment, string fileEx)
        {
            var mem = new MemoryStream();
            var f = new FileStream(vstsAttachment.Uri.LocalPath, FileMode.Open, FileAccess.Read);
            mem.SetLength(f.Length);

            f.Read(mem.GetBuffer(), 0, (int)f.Length -1);

            var mime = MimeTypes.GetMimeTypeByExtension(fileEx) ?? MimeTypes.Binary;

            var binaryAttachment = new BinaryAttachment(vstsAttachment.Description, mime, mem.ToArray());

            f.Close();
            mem.Close();

            return binaryAttachment;
          
        }
 private static StringBuilder GetFileAsString(UriDataAttachment vstsAttachment)
 {
     var sb = new StringBuilder();
     using (var sr = new StreamReader(vstsAttachment.Uri.LocalPath))
     {
         String line;
         while ((line = sr.ReadLine()) != null)
         {
             sb.AppendLine(line);
         }
     }
     return sb;
 }
Exemple #21
0
        public void SendAttachment(string testName, UriDataAttachment attachment, ITeamCityTestWriter testWriter)
        {
            if (testName == null)
            {
                throw new ArgumentNullException(nameof(testName));
            }
            if (attachment == null)
            {
                throw new ArgumentNullException(nameof(attachment));
            }
            if (testWriter == null)
            {
                throw new ArgumentNullException(nameof(testWriter));
            }

            if (!_options.MetadataEnable || !_options.AllowExperimental || _options.Version.CompareTo(_options.TestMetadataSupportVersion) < 0)
            {
                testWriter.WriteStdOutput($"Attachment \"{attachment.Description}\": \"{attachment.Uri}\"");
                return;
            }

            if (!attachment.Uri.IsFile)
            {
                return;
            }

            var filePath = attachment.Uri.LocalPath;

            if (string.IsNullOrEmpty(filePath))
            {
                return;
            }

            var description = attachment.Description ?? string.Empty;

            if (description == filePath)
            {
                description = string.Empty;
            }

            var    fileName      = Path.GetFileName(filePath);
            var    fileExtension = Path.GetExtension(fileName).ToLowerInvariant();
            string artifactDir   = null;

            if (!string.IsNullOrEmpty(description))
            {
                var match = AttachmentDescriptionRegex.Match(description);
                if (match.Success)
                {
                    description = match.Groups[1].Value.Trim();
                    artifactDir = match.Groups[2].Value.Trim();
                }
            }

            if (artifactDir == null)
            {
                var testDirName = new string(NormalizeTestName(testName).ToArray());
                artifactDir = ".teamcity/VSTest/" + testDirName + "/" + _idGenerator.NewId();
            }

            _rootWriter.PublishArtifact(filePath + " => " + artifactDir);
            var artifact = artifactDir + "/" + fileName;

            switch (fileExtension)
            {
            case ".bmp":
            case ".gif":
            case ".ico":
            case ".jng":
            case ".jpeg":
            case ".jpg":
            case ".jfif":
            case ".jp2":
            case ".jps":
            case ".tga":
            case ".tiff":
            case ".tif":
            case ".svg":
            case ".wmf":
            case ".emf":
            case ".png":
                testWriter.WriteImage(artifact, description);
                break;

            default:
                testWriter.WriteFile(artifact, description);
                break;
            }
        }