Skip to content

Added character escaping for test output. #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 48 additions & 4 deletions DotnetCore.TeamCityLogger/Logger.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace DotnetCore.TeamCityLogger
Expand Down Expand Up @@ -38,17 +39,17 @@ private void TestResultHandler(object sender, TestResultEventArgs e)
{
if (message.Category == TestResultMessage.StandardOutCategory)
{
WriteServiceMessage($"testStdOut name='{testName}'] out='{message.Text}'");
WriteServiceMessage($"testStdOut name='{testName}'] out='{Escape(message.Text)}'");
}
else if (message.Category == TestResultMessage.StandardErrorCategory)
{
WriteServiceMessage($"testStdErr name='{testName}'] out='{message.Text}'");
WriteServiceMessage($"testStdErr name='{testName}'] out='{Escape(message.Text)}'");
}
}

if (e.Result.Outcome == TestOutcome.Failed)
{
WriteServiceMessage($"testFailed name='{testName}' message='{e.Result.ErrorMessage}' details='{e.Result.ErrorStackTrace}'");
WriteServiceMessage($"testFailed name='{testName}' message='{Escape(e.Result.ErrorMessage)}' details='{Escape(e.Result.ErrorStackTrace)}'");
}

WriteServiceMessage($"testFinished name='{testName}' duration='{e.Result.Duration.TotalMilliseconds}'");
Expand Down Expand Up @@ -77,5 +78,48 @@ private static void WriteServiceMessage(string message)
{
Console.WriteLine($"##teamcity[{message.Replace("\r\n","\\r\\n").Replace("\n","\\n")}]");
}

static bool IsAscii(char ch) => ch <= '\x007f';

static string Escape(string value)
{
var sb = new StringBuilder(value.Length);
for (int i = 0; i < value.Length; i++)
{
var ch = value[i];

switch (ch)
{
case '|':
sb.Append("||");
break;
case '\'':
sb.Append("|'");
break;
case '\n':
sb.Append("|n");
break;
case '\r':
sb.Append("|r");
break;
case '[':
sb.Append("|[");
break;
case ']':
sb.Append("|]");
break;
default:
if (IsAscii(ch))
sb.Append(ch);
else
{
sb.Append("|0x");
sb.Append(((int)ch).ToString("x4"));
}
break;
}
}
return sb.ToString();
}
}
}