test: infer gadget name from struct name

Creating the Name() function for every gadget we have is superfluous a
bit, as we're essentially parroting the name of the test itself as
implementation for the function.

So instead of requiring every checker implements `Name', we now default
to returning the type name, but if the Name function exists for the
checker, we invoke it and return the value for that function.

This allows us to only define the function where needed, and not
systematically.
pull/12983/head
Lucas Bajolet 2 years ago
parent b62e8cef9c
commit 045b7b7365

@ -75,7 +75,8 @@ func (pc *packerCommand) Assert(t *testing.T, checks ...Checker) {
for _, check := range checks {
checkErr := check.Check(stdout, stderr, err)
if checkErr != nil {
t.Errorf("check %q failed: %s", check.Name(), checkErr)
checkerName := InferName(check)
t.Errorf("check %q failed: %s", checkerName, checkErr)
}
}
}

@ -2,6 +2,7 @@ package test
import (
"fmt"
"reflect"
"regexp"
"testing"
)
@ -32,7 +33,25 @@ func (s Stream) String() string {
type Checker interface {
Check(stdout, stderr string, err error) error
Name() string
}
func InferName(c Checker) string {
if c == nil {
panic("nil checker - malformed test?")
}
checkerType := reflect.TypeOf(c)
_, ok := checkerType.MethodByName("Name")
if !ok {
return checkerType.String()
}
retVals := reflect.ValueOf(c).MethodByName("Name").Call([]reflect.Value{})
if len(retVals) != 1 {
panic(fmt.Sprintf("Name function called - returned %d values. Must be one string only.", len(retVals)))
}
return retVals[0].String()
}
type MustSucceed struct{}
@ -41,8 +60,13 @@ func (_ MustSucceed) Check(stdout, stderr string, err error) error {
return err
}
func (_ MustSucceed) Name() string {
return "Must succeed"
type MustFail struct{}
func (_ MustFail) Check(stdout, stderr string, err error) error {
if err == nil {
return fmt.Errorf("unexpected command success")
}
return nil
}
// Grep is essentially the equivalent to a normal grep -E on the command line.
@ -93,7 +117,3 @@ func (d Dump) Check(stdout, stderr string, err error) error {
d.t.Logf("stderr: %s", stderr)
return nil
}
func (_ Dump) Name() string {
return "dump"
}

Loading…
Cancel
Save