Stub metadata service for builder tests

This commit is contained in:
Paul Meyer 2020-03-25 18:12:34 +00:00
parent b3e361a139
commit a3b49cdc08
3 changed files with 41 additions and 10 deletions

View File

@ -53,18 +53,20 @@ func TestBuilder_Prepare(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := &Builder{}
withMetadataStub(func() {
b := &Builder{}
_, _, err := b.Prepare(tt.config)
_, _, err := b.Prepare(tt.config)
if (err != nil) != tt.wantErr {
t.Errorf("Builder.Prepare() error = %v, wantErr %v", err, tt.wantErr)
return
}
if (err != nil) != tt.wantErr {
t.Errorf("Builder.Prepare() error = %v, wantErr %v", err, tt.wantErr)
return
}
if tt.validate != nil {
tt.validate(b.config)
}
if tt.validate != nil {
tt.validate(b.config)
}
})
})
}
}

View File

@ -0,0 +1,18 @@
package chroot
import "github.com/hashicorp/packer/builder/azure/common/client"
func withMetadataStub(f func()) {
mdc := client.DefaultMetadataClient
defer func() { client.DefaultMetadataClient = mdc }()
client.DefaultMetadataClient = client.MetadataClientStub{
ComputeInfo: client.ComputeInfo{
SubscriptionID: "testSubscriptionID",
ResourceGroupName: "testResourceGroup",
Name: "testVM",
Location: "testLocation",
},
}
f()
}

View File

@ -12,11 +12,22 @@ import (
// DefaultMetadataClient is the default instance metadata client for Azure. Replace this variable for testing purposes only
var DefaultMetadataClient = NewMetadataClient()
// MetadataClient holds methods that Packer uses to get information about the current VM
// MetadataClientAPI holds methods that Packer uses to get information about the current VM
type MetadataClientAPI interface {
GetComputeInfo() (*ComputeInfo, error)
}
// MetadataClientStub is an easy way to put a test hook in DefaultMetadataClient
type MetadataClientStub struct {
ComputeInfo
}
//GetComputeInfo implements MetadataClientAPI
func (s MetadataClientStub) GetComputeInfo() (*ComputeInfo, error) {
return &s.ComputeInfo, nil
}
// ComputeInfo defines the Azure VM metadata that is used in Packer
type ComputeInfo struct {
Name string
ResourceGroupName string