From 0d2363a058a0b567d2e7d4971df7bfe5238d8654 Mon Sep 17 00:00:00 2001 From: James Bardin Date: Fri, 28 Jun 2019 12:09:50 -0400 Subject: [PATCH] add tests to preserve existing Set nil behavior While it may not be intuitive, providers expect that setting a `nil` value will appear as an empty string in state. --- builtin/providers/test/resource.go | 8 ++++++ builtin/providers/test/resource_test.go | 36 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/builtin/providers/test/resource.go b/builtin/providers/test/resource.go index 09732d421..b05fcc681 100644 --- a/builtin/providers/test/resource.go +++ b/builtin/providers/test/resource.go @@ -202,6 +202,14 @@ func testResourceRead(d *schema.ResourceData, meta interface{}) error { d.Set("set", []interface{}{}) } + // This mimics many providers always setting a *string value. + // The existing behavior is that this will appear in the state as an empty + // string, which we have to maintain. + o := d.Get("optional") + if o == "" { + d.Set("optional", nil) + } + // This should not show as set unless it's set in the config _, ok := d.GetOkExists("get_ok_exists_false") if ok { diff --git a/builtin/providers/test/resource_test.go b/builtin/providers/test/resource_test.go index 8b78bb415..9277e9f62 100644 --- a/builtin/providers/test/resource_test.go +++ b/builtin/providers/test/resource_test.go @@ -1050,3 +1050,39 @@ resource "test_resource" "foo" { }, }) } + +func TestResource_unsetNil(t *testing.T) { + resource.UnitTest(t, resource.TestCase{ + Providers: testAccProviders, + CheckDestroy: testAccCheckResourceDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: strings.TrimSpace(` +resource "test_resource" "foo" { + required = "yep" + required_map = { + key = "value" + } + optional = "a" +} + `), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("test_resource.foo", "optional", "a"), + ), + }, + resource.TestStep{ + Config: strings.TrimSpace(` +resource "test_resource" "foo" { + required = "yep" + required_map = { + key = "value" + } +} + `), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("test_resource.foo", "optional", ""), + ), + }, + }, + }) +}