helper/schema: if no ID is set then return nil

This commit is contained in:
Mitchell Hashimoto 2014-08-21 22:19:33 -07:00
parent 3d3789920d
commit 37cf52fa27
3 changed files with 25 additions and 2 deletions

View File

@ -108,7 +108,7 @@ func (r *Resource) Refresh(
err = r.Read(data, meta) err = r.Read(data, meta)
state := data.State() state := data.State()
if state.ID == "" { if state != nil && state.ID == "" {
state = nil state = nil
} }

View File

@ -141,6 +141,13 @@ func (d *ResourceData) SetDependencies(ds []terraform.ResourceDependency) {
func (d *ResourceData) State() *terraform.ResourceState { func (d *ResourceData) State() *terraform.ResourceState {
var result terraform.ResourceState var result terraform.ResourceState
result.ID = d.Id() result.ID = d.Id()
// If we have no ID, then this resource doesn't exist and we just
// return nil.
if result.ID == "" {
return nil
}
result.Attributes = d.stateObject("", d.schema) result.Attributes = d.stateObject("", d.schema)
result.ConnInfo = d.ConnInfo() result.ConnInfo = d.ConnInfo()
result.Dependencies = d.Dependencies() result.Dependencies = d.Dependencies()

View File

@ -1524,7 +1524,21 @@ func TestResourceDataState(t *testing.T) {
} }
} }
// Set an ID so that the state returned is not nil
idSet := false
if d.Id() == "" {
idSet = true
d.SetId("foo")
}
actual := d.State() actual := d.State()
// If we set an ID, then undo what we did so the comparison works
if actual != nil && idSet {
actual.ID = ""
delete(actual.Attributes, "id")
}
if !reflect.DeepEqual(actual, tc.Result) { if !reflect.DeepEqual(actual, tc.Result) {
t.Fatalf("Bad: %d\n\n%#v", i, actual) t.Fatalf("Bad: %d\n\n%#v", i, actual)
} }
@ -1533,6 +1547,7 @@ func TestResourceDataState(t *testing.T) {
func TestResourceDataSetConnInfo(t *testing.T) { func TestResourceDataSetConnInfo(t *testing.T) {
d := &ResourceData{} d := &ResourceData{}
d.SetId("foo")
d.SetConnInfo(map[string]string{ d.SetConnInfo(map[string]string{
"foo": "bar", "foo": "bar",
}) })
@ -1549,6 +1564,7 @@ func TestResourceDataSetConnInfo(t *testing.T) {
func TestResourceDataSetDependencies(t *testing.T) { func TestResourceDataSetDependencies(t *testing.T) {
d := &ResourceData{} d := &ResourceData{}
d.SetId("foo")
d.SetDependencies([]terraform.ResourceDependency{ d.SetDependencies([]terraform.ResourceDependency{
terraform.ResourceDependency{ID: "foo"}, terraform.ResourceDependency{ID: "foo"},
}) })
@ -1580,7 +1596,7 @@ func TestResourceDataSetId_clear(t *testing.T) {
d.SetId("") d.SetId("")
actual := d.State() actual := d.State()
if actual.ID != "" { if actual != nil {
t.Fatalf("bad: %#v", actual) t.Fatalf("bad: %#v", actual)
} }
} }