github.phpd.cn/hashicorp/packer@v1.3.2/builder/docker/step_export_test.go (about) 1 package docker 2 3 import ( 4 "bytes" 5 "context" 6 "errors" 7 "io/ioutil" 8 "os" 9 "testing" 10 11 "github.com/hashicorp/packer/helper/multistep" 12 ) 13 14 func testStepExportState(t *testing.T) multistep.StateBag { 15 state := testState(t) 16 state.Put("container_id", "foo") 17 return state 18 } 19 20 func TestStepExport_impl(t *testing.T) { 21 var _ multistep.Step = new(StepExport) 22 } 23 24 func TestStepExport(t *testing.T) { 25 state := testStepExportState(t) 26 step := new(StepExport) 27 defer step.Cleanup(state) 28 29 // Create a tempfile for our output path 30 tf, err := ioutil.TempFile("", "packer") 31 if err != nil { 32 t.Fatalf("err: %s", err) 33 } 34 tf.Close() 35 defer os.Remove(tf.Name()) 36 37 config := state.Get("config").(*Config) 38 config.ExportPath = tf.Name() 39 driver := state.Get("driver").(*MockDriver) 40 driver.ExportReader = bytes.NewReader([]byte("data!")) 41 42 // run the step 43 if action := step.Run(context.Background(), state); action != multistep.ActionContinue { 44 t.Fatalf("bad action: %#v", action) 45 } 46 47 // verify we did the right thing 48 if !driver.ExportCalled { 49 t.Fatal("should've exported") 50 } 51 if driver.ExportID != "foo" { 52 t.Fatalf("bad: %#v", driver.ExportID) 53 } 54 55 // verify the data exported to the file 56 contents, err := ioutil.ReadFile(tf.Name()) 57 if err != nil { 58 t.Fatalf("err: %s", err) 59 } 60 61 if string(contents) != "data!" { 62 t.Fatalf("bad: %#v", string(contents)) 63 } 64 } 65 66 func TestStepExport_error(t *testing.T) { 67 state := testStepExportState(t) 68 step := new(StepExport) 69 defer step.Cleanup(state) 70 71 // Create a tempfile for our output path 72 tf, err := ioutil.TempFile("", "packer") 73 if err != nil { 74 t.Fatalf("err: %s", err) 75 } 76 tf.Close() 77 78 if err := os.Remove(tf.Name()); err != nil { 79 t.Fatalf("err: %s", err) 80 } 81 82 config := state.Get("config").(*Config) 83 config.ExportPath = tf.Name() 84 driver := state.Get("driver").(*MockDriver) 85 driver.ExportError = errors.New("foo") 86 87 // run the step 88 if action := step.Run(context.Background(), state); action != multistep.ActionHalt { 89 t.Fatalf("bad action: %#v", action) 90 } 91 92 // verify we have an error 93 if _, ok := state.GetOk("error"); !ok { 94 t.Fatal("should have error") 95 } 96 97 // verify we didn't make that file 98 if _, err := os.Stat(tf.Name()); err == nil { 99 t.Fatal("export path shouldn't exist") 100 } 101 }