ContainerImage.Pinniped/test/library/cli.go
Matt Moyer cda8bd6e26
Allow running CLI-related integration tests with pre-built binary.
This allows setting `$PINNIPED_TEST_CLI` to point at an existing `pinniped` CLI binary instead of having the test build one on-the-fly. This is more efficient when you're running the tests across many clusters as we do in CI.

Building the CLI from scratch in our CI environment takes 1.5-2 minutes, so this change should save nearly that much time on every test job.

Signed-off-by: Matt Moyer <moyerm@vmware.com>
2021-03-23 17:19:09 -05:00

54 lines
1.4 KiB
Go

// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package library
import (
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"sync"
"testing"
"github.com/stretchr/testify/require"
"go.pinniped.dev/internal/testutil"
)
//nolint: gochecknoglobals
var pinnipedCLIBinaryCache struct {
buf []byte
mutex sync.Mutex
}
// PinnipedCLIPath returns the path to the Pinniped CLI binary, built on demand and cached between tests.
func PinnipedCLIPath(t *testing.T) string {
t.Helper()
// Allow a pre-built binary passed in via $PINNIPED_TEST_CLI. This is how our tests run in CI for efficiency.
if ext, ok := os.LookupEnv("PINNIPED_TEST_CLI"); ok {
t.Log("using externally provided pinniped CLI binary")
return ext
}
pinnipedCLIBinaryCache.mutex.Lock()
defer pinnipedCLIBinaryCache.mutex.Unlock()
path := filepath.Join(testutil.TempDir(t), "pinniped")
if pinnipedCLIBinaryCache.buf != nil {
t.Log("using previously built pinniped CLI binary")
require.NoError(t, ioutil.WriteFile(path, pinnipedCLIBinaryCache.buf, 0500))
return path
}
t.Log("building pinniped CLI binary")
output, err := exec.Command("go", "build", "-o", path, "go.pinniped.dev/cmd/pinniped").CombinedOutput()
require.NoError(t, err, string(output))
// Fill our cache so we don't have to do this again.
pinnipedCLIBinaryCache.buf, err = ioutil.ReadFile(path)
require.NoError(t, err, string(output))
return path
}