github.com/mitchellh/packer@v1.3.2/builder/docker/step_temp_dir_test.go (about)

     1  package docker
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"path/filepath"
     7  	"testing"
     8  
     9  	"github.com/hashicorp/packer/helper/multistep"
    10  	"github.com/hashicorp/packer/packer"
    11  )
    12  
    13  func TestStepTempDir_impl(t *testing.T) {
    14  	var _ multistep.Step = new(StepTempDir)
    15  }
    16  
    17  func testStepTempDir_impl(t *testing.T) string {
    18  	state := testState(t)
    19  	step := new(StepTempDir)
    20  	defer step.Cleanup(state)
    21  
    22  	// sanity test
    23  	if _, ok := state.GetOk("temp_dir"); ok {
    24  		t.Fatalf("temp_dir should not be in state yet")
    25  	}
    26  
    27  	// run the step
    28  	if action := step.Run(context.Background(), state); action != multistep.ActionContinue {
    29  		t.Fatalf("bad action: %#v", action)
    30  	}
    31  
    32  	// Verify that we got the temp dir
    33  	dirRaw, ok := state.GetOk("temp_dir")
    34  	if !ok {
    35  		t.Fatalf("should've made temp_dir")
    36  	}
    37  	dir := dirRaw.(string)
    38  
    39  	if _, err := os.Stat(dir); err != nil {
    40  		t.Fatalf("err: %s", err)
    41  	}
    42  
    43  	// Cleanup
    44  	step.Cleanup(state)
    45  	if _, err := os.Stat(dir); err == nil {
    46  		t.Fatalf("dir should be gone")
    47  	}
    48  
    49  	return dir
    50  }
    51  
    52  func TestStepTempDir(t *testing.T) {
    53  	testStepTempDir_impl(t)
    54  }
    55  
    56  func TestStepTempDir_notmpdir(t *testing.T) {
    57  	tempenv := "PACKER_TMP_DIR"
    58  
    59  	oldenv := os.Getenv(tempenv)
    60  	defer os.Setenv(tempenv, oldenv)
    61  	os.Setenv(tempenv, "")
    62  
    63  	dir1 := testStepTempDir_impl(t)
    64  
    65  	cd, err := packer.ConfigDir()
    66  	if err != nil {
    67  		t.Fatalf("bad ConfigDir")
    68  	}
    69  	td := filepath.Join(cd, "tmp")
    70  	os.Setenv(tempenv, td)
    71  
    72  	dir2 := testStepTempDir_impl(t)
    73  
    74  	if filepath.Dir(dir1) != filepath.Dir(dir2) {
    75  		t.Fatalf("temp base directories do not match: %s %s", filepath.Dir(dir1), filepath.Dir(dir2))
    76  	}
    77  }
    78  
    79  func TestStepTempDir_packertmpdir(t *testing.T) {
    80  	tempenv := "PACKER_TMP_DIR"
    81  
    82  	oldenv := os.Getenv(tempenv)
    83  	defer os.Setenv(tempenv, oldenv)
    84  	os.Setenv(tempenv, ".")
    85  
    86  	dir1 := testStepTempDir_impl(t)
    87  
    88  	abspath, err := filepath.Abs(".")
    89  	if err != nil {
    90  		t.Fatalf("bad absolute path")
    91  	}
    92  	dir2 := filepath.Join(abspath, "tmp")
    93  
    94  	if filepath.Dir(dir1) != filepath.Dir(dir2) {
    95  		t.Fatalf("temp base directories do not match: %s %s", filepath.Dir(dir1), filepath.Dir(dir2))
    96  	}
    97  }