github.com/hashicorp/packer@v1.14.3/provisioner/shell-local/provisioner_acc_test.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package shell_test
     5  
     6  import (
     7  	"fmt"
     8  	"io"
     9  	"os"
    10  	"os/exec"
    11  	"path/filepath"
    12  	"runtime"
    13  	"strings"
    14  	"testing"
    15  
    16  	"github.com/hashicorp/packer-plugin-sdk/acctest/provisioneracc"
    17  	"github.com/hashicorp/packer-plugin-sdk/acctest/testutils"
    18  )
    19  
    20  func fixtureDir() string {
    21  	_, file, _, _ := runtime.Caller(0)
    22  	return filepath.Join(filepath.Dir(file), "test-fixtures")
    23  }
    24  
    25  func loadFile(templateFragmentPath string) (string, error) {
    26  	dir := fixtureDir()
    27  	fragmentAbsPath := filepath.Join(dir, templateFragmentPath)
    28  	fragmentFile, err := os.Open(fragmentAbsPath)
    29  	if err != nil {
    30  		return "", fmt.Errorf("Unable find %s", fragmentAbsPath)
    31  	}
    32  	defer fragmentFile.Close()
    33  
    34  	fragmentString, err := io.ReadAll(fragmentFile)
    35  	if err != nil {
    36  		return "", fmt.Errorf("Unable to read %s", fragmentAbsPath)
    37  	}
    38  
    39  	return string(fragmentString), nil
    40  }
    41  
    42  func IsCompatible(builder string, vmOS string) bool {
    43  	return vmOS == "linux"
    44  }
    45  
    46  func TestAccShellProvisioner_basic(t *testing.T) {
    47  	templateString, err := loadFile("shell-local-provisioner.txt")
    48  	if err != nil {
    49  		t.Fatalf("Couldn't load test fixture; %s", err.Error())
    50  	}
    51  
    52  	testCase := &provisioneracc.ProvisionerTestCase{
    53  		IsCompatible: IsCompatible,
    54  		Name:         "shell-local-provisioner-basic",
    55  		Teardown: func() error {
    56  			testutils.CleanupFiles("test-fixtures/file.txt")
    57  			return nil
    58  		},
    59  		Template: templateString,
    60  		Type:     "shell-local",
    61  		Check: func(buildcommand *exec.Cmd, logfile string) error {
    62  			if buildcommand.ProcessState != nil {
    63  				if buildcommand.ProcessState.ExitCode() != 0 {
    64  					return fmt.Errorf("Bad exit code. Logfile: %s\n", logfile)
    65  				}
    66  			}
    67  			filecontents, err := loadFile("file.txt")
    68  			if err != nil {
    69  				return err
    70  			}
    71  			if !strings.Contains(filecontents, "hello") {
    72  				return fmt.Errorf("file contents were wrong: %s", filecontents)
    73  			}
    74  			return nil
    75  		},
    76  	}
    77  
    78  	provisioneracc.TestProvisionersAgainstBuilders(testCase, t)
    79  }