From 045b7b736555aa5b27ad841042cc8fb97ff56a76 Mon Sep 17 00:00:00 2001 From: Lucas Bajolet Date: Fri, 3 May 2024 11:02:59 -0400 Subject: [PATCH] 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. --- test/commands_test.go | 3 ++- test/gadgets_test.go | 34 +++++++++++++++++++++++++++------- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/test/commands_test.go b/test/commands_test.go index 5bd6df07b..003d26a23 100644 --- a/test/commands_test.go +++ b/test/commands_test.go @@ -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) } } } diff --git a/test/gadgets_test.go b/test/gadgets_test.go index acbf5b820..33412b9ae 100644 --- a/test/gadgets_test.go +++ b/test/gadgets_test.go @@ -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" -}