helper/schema: ResourceProvider.Configure

This commit is contained in:
Mitchell Hashimoto 2014-08-17 15:01:27 -07:00
parent 51a44db6c2
commit eaac13dd9b
2 changed files with 98 additions and 1 deletions

View File

@ -15,7 +15,7 @@ type Provider struct {
Schema map[string]*Schema
Resources map[string]*Resource
Configure ConfigureFunc
ConfigureFunc ConfigureFunc
}
// ConfigureFunc is the function used to configure a Provider.
@ -38,3 +38,27 @@ func (p *Provider) ValidateResource(
return r.Validate(c)
}
// Configure implementation of terraform.ResourceProvider interface.
func (p *Provider) Configure(c *terraform.ResourceConfig) error {
// No configuration
if p.ConfigureFunc == nil {
return nil
}
sm := schemaMap(p.Schema)
// Get a ResourceData for this configuration. To do this, we actually
// generate an intermediary "diff" although that is never exposed.
diff, err := sm.Diff(nil, c)
if err != nil {
return err
}
data, err := sm.Data(nil, diff)
if err != nil {
return err
}
return p.ConfigureFunc(data)
}

View File

@ -1,12 +1,85 @@
package schema
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/config"
"github.com/hashicorp/terraform/terraform"
)
func TestProviderConfigure(t *testing.T) {
cases := []struct {
P *Provider
Config map[string]interface{}
Err bool
}{
{
P: &Provider{},
Config: nil,
Err: false,
},
{
P: &Provider{
Schema: map[string]*Schema{
"foo": &Schema{
Type: TypeInt,
Optional: true,
},
},
ConfigureFunc: func(d *ResourceData) error {
if d.Get("foo").(int) == 42 {
return nil
}
return fmt.Errorf("nope")
},
},
Config: map[string]interface{}{
"foo": 42,
},
Err: false,
},
{
P: &Provider{
Schema: map[string]*Schema{
"foo": &Schema{
Type: TypeInt,
Optional: true,
},
},
ConfigureFunc: func(d *ResourceData) error {
if d.Get("foo").(int) == 42 {
return nil
}
return fmt.Errorf("nope")
},
},
Config: map[string]interface{}{
"foo": 52,
},
Err: true,
},
}
for i, tc := range cases {
c, err := config.NewRawConfig(tc.Config)
if err != nil {
t.Fatalf("err: %s", err)
}
err = tc.P.Configure(terraform.NewResourceConfig(c))
if (err != nil) != tc.Err {
t.Fatalf("%d: %s", i, err)
}
}
}
func TestProviderValidateResource(t *testing.T) {
cases := []struct {
P *Provider