/
junit_formatter.cr
93 lines (76 loc) · 2.09 KB
/
junit_formatter.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
require "xml"
module Spec
# :nodoc:
class JUnitFormatter < Formatter
@output : IO
@results = [] of Spec::Result
@summary = {} of Symbol => Int32
def initialize(@output)
end
def push(context)
end
def pop
end
def before_example(description)
end
def report(result)
current = @summary[result.kind]? || 0
@summary[result.kind] = current + 1
@results << result
end
def finish
io = @output
io << "<testsuite tests=\"#{@results.size}\" \
errors=\"#{@summary[:error]? || 0}\" \
failed=\"#{@summary[:fail]? || 0}\">\n"
@results.each { |r| write_report(r, io) }
io << "</testsuite>"
io.close
end
def self.file(output_dir)
Dir.mkdir_p(output_dir)
output_file_path = File.join(output_dir, "output.xml")
file = File.new(output_file_path, "w")
JUnitFormatter.new(file)
end
# -------- private utility methods
private def write_report(result, io)
io << "<testcase file=\"#{result.file}\" classname=\"#{classname(result)}\" name=\"#{XML.escape(result.description)}\">\n"
if (has_inner_content(result.kind))
tag = inner_content_tag(result.kind)
ex = result.exception
if ex
write_inner_content(tag, ex, io)
else
io << "<#{tag} />\n"
end
end
io << "</testcase>\n"
end
private def has_inner_content(kind)
kind == :fail || kind == :error
end
private def inner_content_tag(kind)
case kind
when :error
:error
when :fail
:failure
end
end
private def write_inner_content(tag, exception, io)
m = exception.message
if m
io << "<#{tag} message=\"#{XML.escape(m)}\">"
else
io << "<#{tag}>"
end
backtrace = exception.backtrace? || ([] of String)
io << XML.escape(backtrace.join("\n"))
io << "</#{tag}>\n"
end
private def classname(result)
result.file.sub(%r{\.[^/.]+\Z}, "").gsub("/", ".").gsub(/\A\.+|\.+\Z/, "")
end
end
end