...

Source file src/github.com/bazelbuild/rules_go/go/tools/bzltestutil/test2json.go

Documentation: github.com/bazelbuild/rules_go/go/tools/bzltestutil

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

View as plain text