...

Source file src/edge-infra.dev/third_party/test2json/test2json.go

Documentation: edge-infra.dev/third_party/test2json

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package test2json implements conversion of test binary output to JSON.
     6  // It is used by cmd/test2json and cmd/go.
     7  //
     8  // See the cmd/test2json documentation for details of the JSON encoding.
     9  package test2json
    10  
    11  import (
    12  	"bytes"
    13  	"encoding/json"
    14  	"fmt"
    15  	"io"
    16  	"strconv"
    17  	"strings"
    18  	"time"
    19  	"unicode"
    20  	"unicode/utf8"
    21  )
    22  
    23  // Mode controls details of the conversion.
    24  type Mode int
    25  
    26  const (
    27  	Timestamp Mode = 1 << iota // include Time in events
    28  )
    29  
    30  // event is the JSON struct we emit.
    31  type event struct {
    32  	Time    *time.Time `json:",omitempty"`
    33  	Action  string
    34  	Package string     `json:",omitempty"`
    35  	Test    string     `json:",omitempty"`
    36  	Elapsed *float64   `json:",omitempty"`
    37  	Output  *textBytes `json:",omitempty"`
    38  }
    39  
    40  // textBytes is a hack to get JSON to emit a []byte as a string
    41  // without actually copying it to a string.
    42  // It implements encoding.TextMarshaler, which returns its text form as a []byte,
    43  // and then json encodes that text form as a string (which was our goal).
    44  type textBytes []byte
    45  
    46  func (b textBytes) MarshalText() ([]byte, error) { return b, nil }
    47  
    48  // A Converter holds the state of a test-to-JSON conversion.
    49  // It implements io.WriteCloser; the caller writes test output in,
    50  // and the converter writes JSON output to w.
    51  type Converter struct {
    52  	w          io.Writer  // JSON output stream
    53  	pkg        string     // package to name in events
    54  	mode       Mode       // mode bits
    55  	start      time.Time  // time converter started
    56  	testName   string     // name of current test, for output attribution
    57  	report     []*event   // pending test result reports (nested for subtests)
    58  	result     string     // overall test result if seen
    59  	input      lineBuffer // input buffer
    60  	output     lineBuffer // output buffer
    61  	needMarker bool       // require ^V marker to introduce test framing line
    62  }
    63  
    64  // inBuffer and outBuffer are the input and output buffer sizes.
    65  // They're variables so that they can be reduced during testing.
    66  //
    67  // The input buffer needs to be able to hold any single test
    68  // directive line we want to recognize, like:
    69  //
    70  //	<many spaces> --- PASS: very/nested/s/u/b/t/e/s/t
    71  //
    72  // If anyone reports a test directive line > 4k not working, it will
    73  // be defensible to suggest they restructure their test or test names.
    74  //
    75  // The output buffer must be >= utf8.UTFMax, so that it can
    76  // accumulate any single UTF8 sequence. Lines that fit entirely
    77  // within the output buffer are emitted in single output events.
    78  // Otherwise they are split into multiple events.
    79  // The output buffer size therefore limits the size of the encoding
    80  // of a single JSON output event. 1k seems like a reasonable balance
    81  // between wanting to avoid splitting an output line and not wanting to
    82  // generate enormous output events.
    83  var (
    84  	inBuffer  = 4096
    85  	outBuffer = 1024
    86  )
    87  
    88  // NewConverter returns a "test to json" converter.
    89  // Writes on the returned writer are written as JSON to w,
    90  // with minimal delay.
    91  //
    92  // The writes to w are whole JSON events ending in \n,
    93  // so that it is safe to run multiple tests writing to multiple converters
    94  // writing to a single underlying output stream w.
    95  // As long as the underlying output w can handle concurrent writes
    96  // from multiple goroutines, the result will be a JSON stream
    97  // describing the relative ordering of execution in all the concurrent tests.
    98  //
    99  // The mode flag adjusts the behavior of the converter.
   100  // Passing ModeTime includes event timestamps and elapsed times.
   101  //
   102  // The pkg string, if present, specifies the import path to
   103  // report in the JSON stream.
   104  func NewConverter(w io.Writer, pkg string, mode Mode) *Converter {
   105  	c := new(Converter)
   106  	*c = Converter{
   107  		w:     w,
   108  		pkg:   pkg,
   109  		mode:  mode,
   110  		start: time.Now(),
   111  		input: lineBuffer{
   112  			b:    make([]byte, 0, inBuffer),
   113  			line: c.handleInputLine,
   114  			part: c.output.write,
   115  		},
   116  		output: lineBuffer{
   117  			b:    make([]byte, 0, outBuffer),
   118  			line: c.writeOutputEvent,
   119  			part: c.writeOutputEvent,
   120  		},
   121  	}
   122  	c.writeEvent(&event{Action: "start"})
   123  	return c
   124  }
   125  
   126  // Write writes the test input to the converter.
   127  func (c *Converter) Write(b []byte) (int, error) {
   128  	c.input.write(b)
   129  	return len(b), nil
   130  }
   131  
   132  // Exited marks the test process as having exited with the given error.
   133  func (c *Converter) Exited(err error) {
   134  	if err == nil {
   135  		if c.result != "skip" {
   136  			c.result = "pass"
   137  		}
   138  	} else {
   139  		c.result = "fail"
   140  	}
   141  }
   142  
   143  const marker = byte(0x16) // ^V
   144  
   145  var (
   146  	// printed by test on successful run.
   147  	bigPass = []byte("PASS")
   148  
   149  	// printed by test after a normal test failure.
   150  	bigFail = []byte("FAIL")
   151  
   152  	// printed by 'go test' along with an error if the test binary terminates
   153  	// with an error.
   154  	bigFailErrorPrefix = []byte("FAIL\t")
   155  
   156  	// an === NAME line with no test name, if trailing spaces are deleted
   157  	emptyName     = []byte("=== NAME")
   158  	emptyNameLine = []byte("=== NAME  \n")
   159  
   160  	updates = [][]byte{
   161  		[]byte("=== RUN   "),
   162  		[]byte("=== PAUSE "),
   163  		[]byte("=== CONT  "),
   164  		[]byte("=== NAME  "),
   165  		[]byte("=== PASS  "),
   166  		[]byte("=== FAIL  "),
   167  		[]byte("=== SKIP  "),
   168  	}
   169  
   170  	reports = [][]byte{
   171  		[]byte("--- PASS: "),
   172  		[]byte("--- FAIL: "),
   173  		[]byte("--- SKIP: "),
   174  		[]byte("--- BENCH: "),
   175  	}
   176  
   177  	fourSpace = []byte("    ")
   178  
   179  	skipLinePrefix = []byte("?   \t")
   180  	skipLineSuffix = []byte("\t[no test files]")
   181  )
   182  
   183  // handleInputLine handles a single whole test output line.
   184  // It must write the line to c.output but may choose to do so
   185  // before or after emitting other events.
   186  func (c *Converter) handleInputLine(line []byte) {
   187  	if len(line) == 0 {
   188  		return
   189  	}
   190  	sawMarker := false
   191  	if c.needMarker && line[0] != marker {
   192  		c.output.write(line)
   193  		return
   194  	}
   195  	if line[0] == marker {
   196  		c.output.flush()
   197  		sawMarker = true
   198  		line = line[1:]
   199  	}
   200  
   201  	// Trim is line without \n or \r\n.
   202  	trim := line
   203  	if len(trim) > 0 && trim[len(trim)-1] == '\n' {
   204  		trim = trim[:len(trim)-1]
   205  		if len(trim) > 0 && trim[len(trim)-1] == '\r' {
   206  			trim = trim[:len(trim)-1]
   207  		}
   208  	}
   209  
   210  	// === CONT followed by an empty test name can lose its trailing spaces.
   211  	if bytes.Equal(trim, emptyName) {
   212  		line = emptyNameLine
   213  		trim = line[:len(line)-1]
   214  	}
   215  
   216  	// Final PASS or FAIL.
   217  	if bytes.Equal(trim, bigPass) || bytes.Equal(trim, bigFail) || bytes.HasPrefix(trim, bigFailErrorPrefix) {
   218  		c.flushReport(0)
   219  		c.testName = ""
   220  		c.needMarker = sawMarker
   221  		c.output.write(line)
   222  		if bytes.Equal(trim, bigPass) {
   223  			c.result = "pass"
   224  		} else {
   225  			c.result = "fail"
   226  		}
   227  
   228  		return
   229  	}
   230  
   231  	// Special case for entirely skipped test binary: "?   \tpkgname\t[no test files]\n" is only line.
   232  	// Report it as plain output but remember to say skip in the final summary.
   233  	if bytes.HasPrefix(line, skipLinePrefix) && bytes.HasSuffix(trim, skipLineSuffix) && len(c.report) == 0 {
   234  		c.result = "skip"
   235  	}
   236  
   237  	// "=== RUN   "
   238  	// "=== PAUSE "
   239  	// "=== CONT  "
   240  	actionColon := false
   241  	origLine := line
   242  	ok := false
   243  	indent := 0
   244  	for _, magic := range updates {
   245  		if bytes.HasPrefix(line, magic) {
   246  			ok = true
   247  			break
   248  		}
   249  	}
   250  	if !ok {
   251  		// "--- PASS: "
   252  		// "--- FAIL: "
   253  		// "--- SKIP: "
   254  		// "--- BENCH: "
   255  		// but possibly indented.
   256  		for bytes.HasPrefix(line, fourSpace) {
   257  			line = line[4:]
   258  			indent++
   259  		}
   260  		for _, magic := range reports {
   261  			if bytes.HasPrefix(line, magic) {
   262  				actionColon = true
   263  				ok = true
   264  				break
   265  			}
   266  		}
   267  	}
   268  
   269  	// Not a special test output line.
   270  	if !ok {
   271  		// Lookup the name of the test which produced the output using the
   272  		// indentation of the output as an index into the stack of the current
   273  		// subtests.
   274  		// If the indentation is greater than the number of current subtests
   275  		// then the output must have included extra indentation. We can't
   276  		// determine which subtest produced this output, so we default to the
   277  		// old behaviour of assuming the most recently run subtest produced it.
   278  		if indent > 0 && indent <= len(c.report) {
   279  			c.testName = c.report[indent-1].Test
   280  		}
   281  		c.output.write(origLine)
   282  		return
   283  	}
   284  
   285  	// Parse out action and test name.
   286  	i := 0
   287  	if actionColon {
   288  		i = bytes.IndexByte(line, ':') + 1
   289  	}
   290  	if i == 0 {
   291  		i = len(updates[0])
   292  	}
   293  	action := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(string(line[4:i])), ":"))
   294  	name := strings.TrimSpace(string(line[i:]))
   295  
   296  	e := &event{Action: action}
   297  	if line[0] == '-' { // PASS or FAIL report
   298  		// Parse out elapsed time.
   299  		if i := strings.Index(name, " ("); i >= 0 {
   300  			if strings.HasSuffix(name, "s)") {
   301  				t, err := strconv.ParseFloat(name[i+2:len(name)-2], 64)
   302  				if err == nil {
   303  					if c.mode&Timestamp != 0 {
   304  						e.Elapsed = &t
   305  					}
   306  				}
   307  			}
   308  			name = name[:i]
   309  		}
   310  		if len(c.report) < indent {
   311  			// Nested deeper than expected.
   312  			// Treat this line as plain output.
   313  			c.output.write(origLine)
   314  			return
   315  		}
   316  		// Flush reports at this indentation level or deeper.
   317  		c.needMarker = sawMarker
   318  		c.flushReport(indent)
   319  		e.Test = name
   320  		c.testName = name
   321  		c.report = append(c.report, e)
   322  		c.output.write(origLine)
   323  		return
   324  	}
   325  	// === update.
   326  	// Finish any pending PASS/FAIL reports.
   327  	c.needMarker = sawMarker
   328  	c.flushReport(0)
   329  	c.testName = name
   330  
   331  	if action == "name" {
   332  		// This line is only generated to get c.testName right.
   333  		// Don't emit an event.
   334  		return
   335  	}
   336  
   337  	if action == "pause" {
   338  		// For a pause, we want to write the pause notification before
   339  		// delivering the pause event, just so it doesn't look like the test
   340  		// is generating output immediately after being paused.
   341  		c.output.write(origLine)
   342  	}
   343  	c.writeEvent(e)
   344  	if action != "pause" {
   345  		c.output.write(origLine)
   346  	}
   347  
   348  	return
   349  }
   350  
   351  // flushReport flushes all pending PASS/FAIL reports at levels >= depth.
   352  func (c *Converter) flushReport(depth int) {
   353  	c.testName = ""
   354  	for len(c.report) > depth {
   355  		e := c.report[len(c.report)-1]
   356  		c.report = c.report[:len(c.report)-1]
   357  		c.writeEvent(e)
   358  	}
   359  }
   360  
   361  // Close marks the end of the go test output.
   362  // It flushes any pending input and then output (only partial lines at this point)
   363  // and then emits the final overall package-level pass/fail event.
   364  func (c *Converter) Close() error {
   365  	c.input.flush()
   366  	c.output.flush()
   367  	if c.result != "" {
   368  		e := &event{Action: c.result}
   369  		if c.mode&Timestamp != 0 {
   370  			dt := time.Since(c.start).Round(1 * time.Millisecond).Seconds()
   371  			e.Elapsed = &dt
   372  		}
   373  		c.writeEvent(e)
   374  	}
   375  	return nil
   376  }
   377  
   378  // writeOutputEvent writes a single output event with the given bytes.
   379  func (c *Converter) writeOutputEvent(out []byte) {
   380  	c.writeEvent(&event{
   381  		Action: "output",
   382  		Output: (*textBytes)(&out),
   383  	})
   384  }
   385  
   386  // writeEvent writes a single event.
   387  // It adds the package, time (if requested), and test name (if needed).
   388  func (c *Converter) writeEvent(e *event) {
   389  	e.Package = c.pkg
   390  	if c.mode&Timestamp != 0 {
   391  		t := time.Now()
   392  		e.Time = &t
   393  	}
   394  	if e.Test == "" {
   395  		e.Test = c.testName
   396  	}
   397  	js, err := json.Marshal(e)
   398  	if err != nil {
   399  		// Should not happen - event is valid for json.Marshal.
   400  		fmt.Fprintf(c.w, "testjson internal error: %v\n", err)
   401  		return
   402  	}
   403  	js = append(js, '\n')
   404  	c.w.Write(js)
   405  }
   406  
   407  // A lineBuffer is an I/O buffer that reacts to writes by invoking
   408  // input-processing callbacks on whole lines or (for long lines that
   409  // have been split) line fragments.
   410  //
   411  // It should be initialized with b set to a buffer of length 0 but non-zero capacity,
   412  // and line and part set to the desired input processors.
   413  // The lineBuffer will call line(x) for any whole line x (including the final newline)
   414  // that fits entirely in cap(b). It will handle input lines longer than cap(b) by
   415  // calling part(x) for sections of the line. The line will be split at UTF8 boundaries,
   416  // and the final call to part for a long line includes the final newline.
   417  type lineBuffer struct {
   418  	b    []byte       // buffer
   419  	mid  bool         // whether we're in the middle of a long line
   420  	line func([]byte) // line callback
   421  	part func([]byte) // partial line callback
   422  }
   423  
   424  // write writes b to the buffer.
   425  func (l *lineBuffer) write(b []byte) {
   426  	for len(b) > 0 {
   427  		// Copy what we can into l.b.
   428  		m := copy(l.b[len(l.b):cap(l.b)], b)
   429  		l.b = l.b[:len(l.b)+m]
   430  		b = b[m:]
   431  
   432  		// Process lines in l.b.
   433  		i := 0
   434  		for i < len(l.b) {
   435  			j, w := indexEOL(l.b[i:])
   436  			if j < 0 {
   437  				if !l.mid {
   438  					if j := bytes.IndexByte(l.b[i:], '\t'); j >= 0 {
   439  						if isBenchmarkName(bytes.TrimRight(l.b[i:i+j], " ")) {
   440  							l.part(l.b[i : i+j+1])
   441  							l.mid = true
   442  							i += j + 1
   443  						}
   444  					}
   445  				}
   446  				break
   447  			}
   448  			e := i + j + w
   449  			if l.mid {
   450  				// Found the end of a partial line.
   451  				l.part(l.b[i:e])
   452  				l.mid = false
   453  			} else {
   454  				// Found a whole line.
   455  				l.line(l.b[i:e])
   456  			}
   457  			i = e
   458  		}
   459  
   460  		// Whatever's left in l.b is a line fragment.
   461  		if i == 0 && len(l.b) == cap(l.b) {
   462  			// The whole buffer is a fragment.
   463  			// Emit it as the beginning (or continuation) of a partial line.
   464  			t := trimUTF8(l.b)
   465  			l.part(l.b[:t])
   466  			l.b = l.b[:copy(l.b, l.b[t:])]
   467  			l.mid = true
   468  		}
   469  
   470  		// There's room for more input.
   471  		// Slide it down in hope of completing the line.
   472  		if i > 0 {
   473  			l.b = l.b[:copy(l.b, l.b[i:])]
   474  		}
   475  	}
   476  }
   477  
   478  // indexEOL finds the index of a line ending,
   479  // returning its position and output width.
   480  // A line ending is either a \n or the empty string just before a ^V not beginning a line.
   481  // The output width for \n is 1 (meaning it should be printed)
   482  // but the output width for ^V is 0 (meaning it should be left to begin the next line).
   483  func indexEOL(b []byte) (pos, wid int) {
   484  	for i, c := range b {
   485  		if c == '\n' {
   486  			return i, 1
   487  		}
   488  		if c == marker && i > 0 { // test -v=json emits ^V at start of framing lines
   489  			return i, 0
   490  		}
   491  	}
   492  	return -1, 0
   493  }
   494  
   495  // flush flushes the line buffer.
   496  func (l *lineBuffer) flush() {
   497  	if len(l.b) > 0 {
   498  		// Must be a line without a \n, so a partial line.
   499  		l.part(l.b)
   500  		l.b = l.b[:0]
   501  	}
   502  }
   503  
   504  var benchmark = []byte("Benchmark")
   505  
   506  // isBenchmarkName reports whether b is a valid benchmark name
   507  // that might appear as the first field in a benchmark result line.
   508  func isBenchmarkName(b []byte) bool {
   509  	if !bytes.HasPrefix(b, benchmark) {
   510  		return false
   511  	}
   512  	if len(b) == len(benchmark) { // just "Benchmark"
   513  		return true
   514  	}
   515  	r, _ := utf8.DecodeRune(b[len(benchmark):])
   516  	return !unicode.IsLower(r)
   517  }
   518  
   519  // trimUTF8 returns a length t as close to len(b) as possible such that b[:t]
   520  // does not end in the middle of a possibly-valid UTF-8 sequence.
   521  //
   522  // If a large text buffer must be split before position i at the latest,
   523  // splitting at position trimUTF(b[:i]) avoids splitting a UTF-8 sequence.
   524  func trimUTF8(b []byte) int {
   525  	// Scan backward to find non-continuation byte.
   526  	for i := 1; i < utf8.UTFMax && i <= len(b); i++ {
   527  		if c := b[len(b)-i]; c&0xc0 != 0x80 {
   528  			switch {
   529  			case c&0xe0 == 0xc0:
   530  				if i < 2 {
   531  					return len(b) - i
   532  				}
   533  			case c&0xf0 == 0xe0:
   534  				if i < 3 {
   535  					return len(b) - i
   536  				}
   537  			case c&0xf8 == 0xf0:
   538  				if i < 4 {
   539  					return len(b) - i
   540  				}
   541  			}
   542  			break
   543  		}
   544  	}
   545  	return len(b)
   546  }
   547  

View as plain text