Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added trigger imports into time_sleep #341

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions internal/provider/resource_time_sleep.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,12 @@ func (t timeSleepResource) ImportState(ctx context.Context, req resource.ImportS

idParts := strings.Split(id, ",")

if len(idParts) != 2 || (idParts[0] == "" && idParts[1] == "") {
if len(idParts) < 2 || (idParts[0] == "" && idParts[1] == "") {
resp.Diagnostics.AddError(
"Unexpected Format of ID",
fmt.Sprintf("Unexpected format of ID (%q), expected CREATEDURATION,DESTROYDURATION where at least one value is non-empty", id))
fmt.Sprintf(
`Unexpected format of ID (%q), expected CREATEDURATION,DESTROYDURATION,KEY=VALUE,KEY=VALUE... ",
where at least one CREATIONDURATION or DESTROYDURATION value is non-empty`, id))

return
}
Expand Down Expand Up @@ -132,7 +134,23 @@ func (t timeSleepResource) ImportState(ctx context.Context, req resource.ImportS
state.DestroyDuration = types.StringValue(idParts[1])
}

state.Triggers = types.MapValueMust(types.StringType, map[string]attr.Value{})
triggers := map[string]attr.Value{}
// We have triggers defined so we need to parse and import.
if len(idParts) > 2 {
for _, trigger := range idParts[2:] {
value := strings.Split(trigger, "=")
if len(value) != 2 {
resp.Diagnostics.AddError("Trigger import error",
fmt.Sprintf("Trigger import entries must be KEY=VALUE, got %s", trigger),
)
return
}

triggers[value[0]] = types.StringValue(value[1])
}
}

state.Triggers = types.MapValueMust(types.StringType, triggers)

diags := resp.State.Set(ctx, state)
resp.Diagnostics.Append(diags...)
Expand Down
245 changes: 245 additions & 0 deletions internal/provider/resource_time_sleep_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,16 @@ package provider
import (
"context"
"fmt"
"reflect"
"regexp"
"testing"
"time"

"github.com/hashicorp/terraform-plugin-framework-timetypes/timetypes"
"github.com/hashicorp/terraform-plugin-framework/attr"
r "github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-go/tftypes"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/knownvalue"
Expand Down Expand Up @@ -354,6 +358,212 @@ func TestAccTimeSleep_Validators(t *testing.T) {
})
}

// Validate that importing works as expected
func TestResourceTimeSleepImport(t *testing.T) {

// want := timeSleepModelV0{
// CreateDuration: types.StringValue("1s"),
// DestroyDuration: types.StringValue("1s"),
// Triggers: types.MapValueMust(types.StringType, triggers),
// ID: timetypes.NewRFC3339TimeValue(time.Now().UTC()),
// }
var tests = []struct {
name string
id string
want timeSleepModelV0
error bool
summary string
}{
{
name: "just_createduration",
id: "1s,",
want: timeSleepModelV0{
CreateDuration: types.StringValue("1s"),
DestroyDuration: types.StringNull(),
Triggers: types.MapValueMust(types.StringType, map[string]attr.Value{}),
ID: timetypes.NewRFC3339TimeValue(time.Now().UTC()),
},
error: false,
},
{
name: "create_and_destroy_duration_only",
id: "1s,20s",
want: timeSleepModelV0{
CreateDuration: types.StringValue("1s"),
DestroyDuration: types.StringValue("20s"),
Triggers: types.MapValueMust(types.StringType, map[string]attr.Value{}),
ID: timetypes.NewRFC3339TimeValue(time.Now().UTC()),
},
error: false,
},
{
name: "destroy_duration_only",
id: ",20s",
want: timeSleepModelV0{
CreateDuration: types.StringNull(),
DestroyDuration: types.StringValue("20s"),
Triggers: types.MapValueMust(types.StringType, map[string]attr.Value{}),
ID: timetypes.NewRFC3339TimeValue(time.Now().UTC()),
},
error: false,
},
{
name: "create_destroy_single_trigger_only",
id: "1s,1s,test=testvalue",
want: timeSleepModelV0{
CreateDuration: types.StringValue("1s"),
DestroyDuration: types.StringValue("1s"),
Triggers: types.MapValueMust(types.StringType, map[string]attr.Value{
"test": types.StringValue("testvalue"),
}),
ID: timetypes.NewRFC3339TimeValue(time.Now().UTC()),
},
error: false,
},
{
name: "create_destroy_multi",
id: "1s,1s,test1=testvalue1,test2=testvalue2",
want: timeSleepModelV0{
CreateDuration: types.StringValue("1s"),
DestroyDuration: types.StringValue("1s"),
Triggers: types.MapValueMust(types.StringType, map[string]attr.Value{
"test1": types.StringValue("testvalue1"),
"test2": types.StringValue("testvalue2"),
}),
ID: timetypes.NewRFC3339TimeValue(time.Now().UTC()),
},
error: false,
},
{
name: "create_no_destroy_single_only",
id: "1s,,test1=testvalue1",
want: timeSleepModelV0{
CreateDuration: types.StringValue("1s"),
DestroyDuration: types.StringNull(),
Triggers: types.MapValueMust(types.StringType, map[string]attr.Value{
"test1": types.StringValue("testvalue1"),
}),
ID: timetypes.NewRFC3339TimeValue(time.Now().UTC()),
},
error: false,
},
{
name: "no_create_destroy_single_only",
id: ",1s,test1=testvalue1",
want: timeSleepModelV0{
CreateDuration: types.StringNull(),
DestroyDuration: types.StringValue("1s"),
Triggers: types.MapValueMust(types.StringType, map[string]attr.Value{
"test1": types.StringValue("testvalue1"),
}),
ID: timetypes.NewRFC3339TimeValue(time.Now().UTC()),
},
error: false,
},
{
name: "create_destroy_invalid_trigger_format",
id: "1s,1s,test=testvalue,test2==testvalue2",
want: timeSleepModelV0{
CreateDuration: types.StringValue("1s"),
DestroyDuration: types.StringValue("1s"),
Triggers: types.MapValueMust(types.StringType, map[string]attr.Value{
"test": types.StringValue("testvalue"),
}),
ID: timetypes.NewRFC3339TimeValue(time.Now().UTC()),
},
error: true,
summary: "Trigger import error",
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
sleepResource := NewTimeSleepResource()

schemaResponse := r.SchemaResponse{}
sleepResource.Schema(context.Background(), r.SchemaRequest{}, &schemaResponse)

req := r.ImportStateRequest{
ID: test.id,
}

resp := r.ImportStateResponse{
State: tfsdk.State{
Schema: schemaResponse.Schema,
},
Diagnostics: nil,
}

sleepResource.(r.ResourceWithImportState).ImportState(context.Background(), req, &resp)
if resp.Diagnostics.HasError() {
if !test.error {
t.Fatalf("Diags was not empty: %+v", resp.Diagnostics)
}

for _, diag := range resp.Diagnostics {
if diag.Summary() != test.summary {
t.Fatalf("Diags had additional errors that were not expected: %+v", resp.Diagnostics)
}
}
// Passed the test
return
}

state := timeSleepModelV0{}
resp.State.Get(context.Background(), &state)

// This is a bit of a cheat, because the ID of the state object is generated inside the function
// so we need to set the `want` structure to have the right time.
test.want.ID = state.ID

if !reflect.DeepEqual(state, test.want) {
t.Fatal(fmt.Sprintf("Trigger map was not what we expected, want `%+v` got `%+v`", test.want, state))
}
})
}
}

func TestAccTimeSleepImport_Triggers1(t *testing.T) {
resourceName := "time_sleep.test"

resource.UnitTest(t, resource.TestCase{
ProtoV5ProviderFactories: protoV5ProviderFactories(),
CheckDestroy: nil,
Steps: []resource.TestStep{
{
Config: testAccConfigTimeSleepImportTriggers1("key1", "value1"),
ConfigStateChecks: []statecheck.StateCheck{
statecheck.ExpectKnownValue(resourceName, tfjsonpath.New("triggers"), knownvalue.MapSizeExact(1)),
statecheck.ExpectKnownValue(resourceName, tfjsonpath.New("triggers").AtMapKey("key1"), knownvalue.StringExact("value1")),
statecheck.ExpectKnownValue(resourceName, tfjsonpath.New("id"), knownvalue.NotNull()),
statecheck.ExpectKnownValue(resourceName, tfjsonpath.New("create_duration"), knownvalue.NotNull()),
},
},
},
})
}

func TestAccTimeSleepImport_Triggers2(t *testing.T) {
resourceName := "time_sleep.test"

resource.UnitTest(t, resource.TestCase{
ProtoV5ProviderFactories: protoV5ProviderFactories(),
CheckDestroy: nil,
Steps: []resource.TestStep{
{
Config: testAccConfigTimeSleepImportTriggers2("key1", "value1", "key2", "value2"),
ConfigStateChecks: []statecheck.StateCheck{
statecheck.ExpectKnownValue(resourceName, tfjsonpath.New("triggers"), knownvalue.MapSizeExact(2)),
statecheck.ExpectKnownValue(resourceName, tfjsonpath.New("triggers").AtMapKey("key1"), knownvalue.StringExact("value1")),
statecheck.ExpectKnownValue(resourceName, tfjsonpath.New("triggers").AtMapKey("key2"), knownvalue.StringExact("value2")),
statecheck.ExpectKnownValue(resourceName, tfjsonpath.New("id"), knownvalue.NotNull()),
statecheck.ExpectKnownValue(resourceName, tfjsonpath.New("create_duration"), knownvalue.NotNull()),
},
},
},
})
}

//func testAccTimeSleepImportStateIdFunc(resourceName string) resource.ImportStateIdFunc {
// return func(s *terraform.State) (string, error) {
// rs, ok := s.RootModule().Resources[resourceName]
Expand Down Expand Up @@ -395,3 +605,38 @@ resource "time_sleep" "test" {
}
`, keeperKey1, keeperKey2)
}

func testAccConfigTimeSleepImportTriggers1(keeperKey1 string, keeperKey2 string) string {
return fmt.Sprintf(`
import {
to = time_sleep.test
id = "1s,,%s=%s"
}

resource "time_sleep" "test" {
create_duration = "1s"

triggers = {
%[1]q = %[2]q
}
}
`, keeperKey1, keeperKey2)
}

func testAccConfigTimeSleepImportTriggers2(keeperKey1 string, keeperKey2 string, keeperKey3 string, keeperKey4 string) string {
return fmt.Sprintf(`
import {
to = time_sleep.test
id = "1s,,%s=%s,%s=%s"
}

resource "time_sleep" "test" {
create_duration = "1s"

triggers = {
%[1]q = %[2]q
%[3]q = %[4]q
}
}
`, keeperKey1, keeperKey2, keeperKey3, keeperKey4)
}