github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/pkg/vmtest/internal/json2test/testcollector.go (about)

     1  // Copyright 2019 the u-root 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 json2test
     6  
     7  import (
     8  	"fmt"
     9  	"log"
    10  	"sync"
    11  )
    12  
    13  type TestState string
    14  
    15  const (
    16  	StateSkip    TestState = "skip"
    17  	StateFail    TestState = "fail"
    18  	StatePass    TestState = "pass"
    19  	StatePaused  TestState = "paused"
    20  	StateRunning TestState = "running"
    21  )
    22  
    23  var actionToState = map[Action]TestState{
    24  	Skip:     StateSkip,
    25  	Fail:     StateFail,
    26  	Pass:     StatePass,
    27  	Pause:    StatePaused,
    28  	Run:      StateRunning,
    29  	Continue: StateRunning,
    30  }
    31  
    32  type TestKind int
    33  
    34  const (
    35  	KindTest TestKind = iota
    36  	KindBenchmark
    37  )
    38  
    39  // TestResult is an individual tests' outcome.
    40  type TestResult struct {
    41  	Kind       TestKind
    42  	State      TestState
    43  	FullOutput string
    44  }
    45  
    46  type TestCollector struct {
    47  	mu sync.Mutex
    48  
    49  	// Package collects all output for a particular package.
    50  	Packages map[string]string
    51  
    52  	// Tests are indexed by fully-qualified packageName.TestName strings.
    53  	Tests map[string]*TestResult
    54  }
    55  
    56  // NewTestCollector returns a Handler that collects test results.
    57  func NewTestCollector() *TestCollector {
    58  	return &TestCollector{
    59  		Packages: make(map[string]string),
    60  		Tests:    make(map[string]*TestResult),
    61  	}
    62  }
    63  
    64  // Handle implements Handler.
    65  func (tc *TestCollector) Handle(e TestEvent) {
    66  	tc.mu.Lock()
    67  	defer tc.mu.Unlock()
    68  
    69  	if _, ok := tc.Packages[e.Package]; !ok {
    70  		tc.Packages[e.Package] = ""
    71  	}
    72  	tc.Packages[e.Package] += e.Output
    73  
    74  	if len(e.Test) == 0 {
    75  		return
    76  	}
    77  
    78  	testName := fmt.Sprintf("%s.%s", e.Package, e.Test)
    79  	t, ok := tc.Tests[testName]
    80  	if !ok {
    81  		t = &TestResult{
    82  			Kind: KindTest,
    83  		}
    84  		tc.Tests[testName] = t
    85  	}
    86  
    87  	switch e.Action {
    88  	case Benchmark:
    89  		t.Kind = KindBenchmark
    90  	case Output:
    91  	default:
    92  		s, ok := actionToState[e.Action]
    93  		if !ok {
    94  			log.Printf("Unknown action %q in event %v", e.Action, e)
    95  		}
    96  		t.State = s
    97  	}
    98  	t.FullOutput = t.FullOutput + e.Output
    99  }