From ded05001099c18a1168e9a780b38ef07990558cf Mon Sep 17 00:00:00 2001 From: Lucas Bajolet Date: Tue, 6 Aug 2024 10:43:38 -0400 Subject: [PATCH] packer_test: add plugins used gadget When testing a packer build or validate, one common use case is to check which plugins are loaded and used by Packer to run a command. This is generally done through Grep, but repeating the same pattern can be redundant, and if the output changes, all those need to be updated. Therefore, this commit introduces a PluginsUsed gadget, which can be orchestrated to ensure a plugin is used, or not used, allowing to check for multiple plugins at once. --- packer_test/lib/gadgets.go | 54 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/packer_test/lib/gadgets.go b/packer_test/lib/gadgets.go index ccccb4e2be9..d1b16d254ab 100644 --- a/packer_test/lib/gadgets.go +++ b/packer_test/lib/gadgets.go @@ -5,6 +5,9 @@ import ( "reflect" "strings" "testing" + + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/go-version" ) type Stream int @@ -122,6 +125,57 @@ func Grep(expression string, opts ...GrepOpts) Checker { return pc } +type PluginVersionTuple struct { + Source string + Version *version.Version +} + +func NewPluginVersionTuple(src, pluginVersion string) PluginVersionTuple { + ver := version.Must(version.NewVersion(pluginVersion)) + return PluginVersionTuple{ + Source: src, + Version: ver, + } +} + +type pluginsUsed struct { + invert bool + plugins []PluginVersionTuple +} + +func (pu pluginsUsed) Check(stdout, stderr string, _ error) error { + var opts []GrepOpts + if !pu.invert { + opts = append(opts, GrepInvert) + } + + var retErr error + + for _, pvt := range pu.plugins { + // `error` is ignored for Grep, so we can pass in nil + err := Grep( + fmt.Sprintf("%s_v%s[^:]+\\\\s*plugin process exited", pvt.Source, pvt.Version.Core()), + opts..., + ).Check(stdout, stderr, nil) + if err != nil { + retErr = multierror.Append(retErr, err) + } + } + + return retErr +} + +// PluginsUsed is a glorified `Grep` checker that looks for a bunch of plugins +// used from the logs of a packer build or packer validate. +// +// Each tuple passed as parameter is looked for in the logs using Grep +func PluginsUsed(invert bool, plugins ...PluginVersionTuple) Checker { + return pluginsUsed{ + invert: invert, + plugins: plugins, + } +} + func Dump(t *testing.T) Checker { return &dump{t} }