junit: Add Testsuites.WriteXML method

This commit is contained in:
Joël Stemmer 2022-09-27 21:04:24 +01:00
parent b1271c39f9
commit 075629ad5f
3 changed files with 44 additions and 14 deletions

View File

@ -64,32 +64,21 @@ func (c Config) Run(input io.Reader, output io.Writer) (*gtr.Report, error) {
} }
} }
if err = c.writeXML(output, report); err != nil { if err = c.writeJunitXML(output, report); err != nil {
return nil, err return nil, err
} }
return &report, nil return &report, nil
} }
func (c Config) writeXML(w io.Writer, report gtr.Report) error { func (c Config) writeJunitXML(w io.Writer, report gtr.Report) error {
testsuites := junit.CreateFromReport(report, c.Hostname) testsuites := junit.CreateFromReport(report, c.Hostname)
if !c.SkipXMLHeader { if !c.SkipXMLHeader {
_, err := fmt.Fprintf(w, xml.Header) _, err := fmt.Fprintf(w, xml.Header)
if err != nil { if err != nil {
return err return err
} }
} }
return testsuites.WriteXML(w)
enc := xml.NewEncoder(w)
enc.Indent("", "\t")
if err := enc.Encode(testsuites); err != nil {
return err
}
if err := enc.Flush(); err != nil {
return err
}
_, err := fmt.Fprintf(w, "\n")
return err
} }
func (c Config) gotestOptions() []gotest.Option { func (c Config) gotestOptions() []gotest.Option {

View File

@ -5,6 +5,7 @@ package junit
import ( import (
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"io"
"strings" "strings"
"time" "time"
@ -36,6 +37,20 @@ func (t *Testsuites) AddSuite(ts Testsuite) {
t.Disabled += ts.Disabled t.Disabled += ts.Disabled
} }
// WriteXML writes the XML representation of Testsuites t to writer w.
func (t *Testsuites) WriteXML(w io.Writer) error {
enc := xml.NewEncoder(w)
enc.Indent("", "\t")
if err := enc.Encode(t); err != nil {
return err
}
if err := enc.Flush(); err != nil {
return err
}
_, err := fmt.Fprintf(w, "\n")
return err
}
// Testsuite is a single JUnit testsuite containing testcases. // Testsuite is a single JUnit testsuite containing testcases.
type Testsuite struct { type Testsuite struct {
// required attributes // required attributes

View File

@ -1,6 +1,7 @@
package junit package junit
import ( import (
"bytes"
"encoding/xml" "encoding/xml"
"testing" "testing"
"time" "time"
@ -181,3 +182,28 @@ func TestMarshalUnmarshal(t *testing.T) {
t.Errorf("Unmarshal result incorrect, diff (-want +got):\n%s\n", diff) t.Errorf("Unmarshal result incorrect, diff (-want +got):\n%s\n", diff)
} }
} }
func TestWriteXML(t *testing.T) {
want := `<testsuites tests="1">
<testsuite name="Example" tests="1" failures="0" errors="0" id="0" time="">
<testcase name="Test" classname=""></testcase>
</testsuite>
</testsuites>
`
var suites Testsuites
ts := Testsuite{Name:"Example"}
ts.AddTestcase(Testcase{Name: "Test", })
suites.AddSuite(ts)
var buf bytes.Buffer
if err := suites.WriteXML(&buf); err != nil {
t.Fatalf("WriteXML failed: %v\n", err)
}
got := buf.String()
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("WriteXML mismatch, diff (-want +got):\n%s\n", diff)
}
}