From 2b06d74019c510a3611996528cfa5abdb23d6819 Mon Sep 17 00:00:00 2001 From: Adrien Delorme Date: Mon, 8 Apr 2019 13:38:55 +0200 Subject: [PATCH] add a sleep provisioner mainly for testing purposes --- provisioner/sleep/provisioner.go | 30 ++++++++++++++ provisioner/sleep/provisioner_test.go | 56 +++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 provisioner/sleep/provisioner.go create mode 100644 provisioner/sleep/provisioner_test.go diff --git a/provisioner/sleep/provisioner.go b/provisioner/sleep/provisioner.go new file mode 100644 index 000000000..146ac914d --- /dev/null +++ b/provisioner/sleep/provisioner.go @@ -0,0 +1,30 @@ +package sleep + +import ( + "context" + "time" + + "github.com/hashicorp/packer/helper/config" + "github.com/hashicorp/packer/packer" +) + +type Provisioner struct { + Duration time.Duration +} + +var _ packer.Provisioner = new(Provisioner) + +func (p *Provisioner) Prepare(raws ...interface{}) error { + return config.Decode(&p, &config.DecodeOpts{}, raws...) +} + +func (p *Provisioner) Provision(ctx context.Context, _ packer.Ui, _ packer.Communicator) error { + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(p.Duration): + return nil + } +} + +func (p *Provisioner) Cancel() {} diff --git a/provisioner/sleep/provisioner_test.go b/provisioner/sleep/provisioner_test.go new file mode 100644 index 000000000..afc0d162c --- /dev/null +++ b/provisioner/sleep/provisioner_test.go @@ -0,0 +1,56 @@ +package sleep + +import ( + "context" + "testing" + "time" +) + +func test1sConfig() map[string]interface{} { + return map[string]interface{}{ + "duration": "1s", + } +} + +func TestConfigPrepare_1s(t *testing.T) { + raw := test1sConfig() + var p Provisioner + err := p.Prepare(raw) + if err != nil { + t.Fatalf("prerare failed: %v", err) + } + + if p.Duration != time.Second { + t.Fatal("wrong duration") + } +} + +func TestProvisioner_Provision(t *testing.T) { + ctxCancelled, cancel := context.WithCancel(context.Background()) + cancel() + type fields struct { + Duration time.Duration + } + type args struct { + ctx context.Context + } + tests := []struct { + name string + fields fields + args args + wantErr bool + }{ + {"valid sleep", fields{time.Millisecond}, args{context.Background()}, false}, + {"timeout", fields{time.Millisecond}, args{ctxCancelled}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + p := &Provisioner{ + Duration: tt.fields.Duration, + } + if err := p.Provision(tt.args.ctx, nil, nil); (err != nil) != tt.wantErr { + t.Errorf("Provisioner.Provision() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +}