github.com/elek/golangci-lint@v1.42.2-0.20211208090441-c05b7fcb3a9a/pkg/printers/junitxml.go (about)

     1  package printers
     2  
     3  import (
     4  	"context"
     5  	"encoding/xml"
     6  	"strings"
     7  
     8  	"github.com/elek/golangci-lint/pkg/logutils"
     9  	"github.com/elek/golangci-lint/pkg/result"
    10  )
    11  
    12  type testSuitesXML struct {
    13  	XMLName    xml.Name `xml:"testsuites"`
    14  	TestSuites []testSuiteXML
    15  }
    16  
    17  type testSuiteXML struct {
    18  	XMLName   xml.Name      `xml:"testsuite"`
    19  	Suite     string        `xml:"name,attr"`
    20  	Tests     int           `xml:"tests,attr"`
    21  	Errors    int           `xml:"errors,attr"`
    22  	Failures  int           `xml:"failures,attr"`
    23  	TestCases []testCaseXML `xml:"testcase"`
    24  }
    25  
    26  type testCaseXML struct {
    27  	Name      string     `xml:"name,attr"`
    28  	ClassName string     `xml:"classname,attr"`
    29  	Failure   failureXML `xml:"failure"`
    30  }
    31  
    32  type failureXML struct {
    33  	Message string `xml:"message,attr"`
    34  	Content string `xml:",cdata"`
    35  }
    36  
    37  type JunitXML struct {
    38  }
    39  
    40  func NewJunitXML() *JunitXML {
    41  	return &JunitXML{}
    42  }
    43  
    44  func (JunitXML) Print(ctx context.Context, issues []result.Issue) error {
    45  	suites := make(map[string]testSuiteXML) // use a map to group by file
    46  
    47  	for ind := range issues {
    48  		i := &issues[ind]
    49  		suiteName := i.FilePath()
    50  		testSuite := suites[suiteName]
    51  		testSuite.Suite = i.FilePath()
    52  		testSuite.Tests++
    53  		testSuite.Failures++
    54  
    55  		tc := testCaseXML{
    56  			Name:      i.FromLinter,
    57  			ClassName: i.Pos.String(),
    58  			Failure: failureXML{
    59  				Message: i.Text,
    60  				Content: strings.Join(i.SourceLines, "\n"),
    61  			},
    62  		}
    63  
    64  		testSuite.TestCases = append(testSuite.TestCases, tc)
    65  		suites[suiteName] = testSuite
    66  	}
    67  
    68  	var res testSuitesXML
    69  	for _, val := range suites {
    70  		res.TestSuites = append(res.TestSuites, val)
    71  	}
    72  
    73  	enc := xml.NewEncoder(logutils.StdOut)
    74  	enc.Indent("", "  ")
    75  	if err := enc.Encode(res); err != nil {
    76  		return err
    77  	}
    78  	return nil
    79  }