Skip to content

Commit 84a5190

Browse files
authored
Escape illegal XML characters in junit output (#140)
1 parent 97e0285 commit 84a5190

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

junit/junit.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,5 +236,27 @@ func formatDuration(d time.Duration) string {
236236

237237
// formatOutput combines the lines from the given output into a single string.
238238
func formatOutput(output []string) string {
239-
return strings.Join(output, "\n")
239+
return escapeIllegalChars(strings.Join(output, "\n"))
240+
}
241+
242+
func escapeIllegalChars(str string) string {
243+
return strings.Map(func(r rune) rune {
244+
if isInCharacterRange(r) {
245+
return r
246+
}
247+
return '�'
248+
}, str)
249+
}
250+
251+
// Decide whether the given rune is in the XML Character Range, per
252+
// the Char production of https://www.xml.com/axml/testaxml.htm,
253+
// Section 2.2 Characters.
254+
// Form: encoding/xml/xml.go
255+
func isInCharacterRange(r rune) (inrange bool) {
256+
return r == 0x09 ||
257+
r == 0x0A ||
258+
r == 0x0D ||
259+
r >= 0x20 && r <= 0xD7FF ||
260+
r >= 0xE000 && r <= 0xFFFD ||
261+
r >= 0x10000 && r <= 0x10FFFF
240262
}

junit/junit_test.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ func TestCreateFromReport(t *testing.T) {
2626
Result: gtr.Pass,
2727
Output: []string{"ok"},
2828
},
29+
{
30+
Name: "TestEscapeOutput",
31+
Result: gtr.Pass,
32+
Output: []string{"\x00\v\f \t\\"},
33+
},
2934
{
3035
Name: "TestFail",
3136
Result: gtr.Fail,
@@ -47,14 +52,14 @@ func TestCreateFromReport(t *testing.T) {
4752
}
4853

4954
want := Testsuites{
50-
Tests: 6,
55+
Tests: 7,
5156
Errors: 3,
5257
Failures: 1,
5358
Skipped: 1,
5459
Suites: []Testsuite{
5560
{
5661
Name: "package/name",
57-
Tests: 6,
62+
Tests: 7,
5863
Errors: 3,
5964
ID: 0,
6065
Failures: 1,
@@ -72,6 +77,12 @@ func TestCreateFromReport(t *testing.T) {
7277
Time: "0.000",
7378
SystemOut: &Output{Data: "ok"},
7479
},
80+
{
81+
Name: "TestEscapeOutput",
82+
Classname: "package/name",
83+
Time: "0.000",
84+
SystemOut: &Output{Data: `��� \`},
85+
},
7586
{
7687
Name: "TestFail",
7788
Classname: "package/name",

0 commit comments

Comments
 (0)