From 707e40e2e65d0c84fcd1ff6fe7b24472fc31e132 Mon Sep 17 00:00:00 2001 From: Lucas Bajolet Date: Wed, 15 May 2024 16:20:35 -0400 Subject: [PATCH] packer_test: add func for "manual" plugin install Installing a plugin manually to a directory is something needed for some tests, especially those not relying on packer commands to install plugins as they reject/correct the path/version. Therefore this function is introduced so we have an easy way to install a binary as a plugin somewhere on the provided plugin directory. --- packer_test/plugin_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/packer_test/plugin_test.go b/packer_test/plugin_test.go index 80ba4e2c8..f3376f874 100644 --- a/packer_test/plugin_test.go +++ b/packer_test/plugin_test.go @@ -1,12 +1,14 @@ package packer_test import ( + "crypto/sha256" "fmt" "io" "os" "os/exec" "path/filepath" "runtime" + "strings" "sync" "testing" @@ -297,3 +299,39 @@ func TempWorkdir(t *testing.T, files ...string) (string, func()) { } } } + +// SHA256Sum computes the SHA256 digest for an input file +// +// The digest is returned as a hexstring +func SHA256Sum(t *testing.T, file string) string { + fl, err := os.ReadFile(file) + if err != nil { + t.Fatalf("failed to compute sha256sum for %q: %s", file, err) + } + sha := sha256.New() + sha.Write(fl) + return fmt.Sprintf("%x", sha.Sum([]byte{})) +} + +// ManualPluginInstall emulates how Packer installs plugins with `packer plugins install` +// +// This is used for some tests if we want to install a plugin that cannot be installed +// through the normal commands (typically because Packer rejects it). +func ManualPluginInstall(t *testing.T, dest, srcPlugin, versionStr string) { + err := os.MkdirAll(dest, 0755) + if err != nil { + t.Fatalf("failed to create destination directories %q: %s", dest, err) + } + + pluginName := ExpectedInstalledName(versionStr) + destPath := filepath.Join(dest, pluginName) + + CopyFile(t, destPath, srcPlugin) + + shaPath := destPath + if runtime.GOOS == "windows" { + shaPath = strings.Replace(destPath, ".exe", "", 1) + } + shaPath = fmt.Sprintf("%s_SHA256SUM", shaPath) + WriteFile(t, shaPath, SHA256Sum(t, destPath)) +}