Skip to content

Commit

Permalink
chore: utility to convert labels to hcloud-go types (#892)
Browse files Browse the repository at this point in the history
We often have to convert between the Terraform Plugin Framework and
hcloud-go representations for labels.

Will be used by #817
  • Loading branch information
apricote authored Mar 11, 2024
1 parent 68e366e commit 7d8bf6e
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
19 changes: 19 additions & 0 deletions internal/util/hcloudutil/labels.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package hcloudutil

import (
"context"

"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
)

func TerraformLabelsToHCloud(ctx context.Context, inputLabels types.Map, outputLabels *map[string]string) diag.Diagnostics {
var diagnostics diag.Diagnostics
*outputLabels = make(map[string]string, len(inputLabels.Elements()))

if !inputLabels.IsNull() {
diagnostics.Append(inputLabels.ElementsAs(ctx, outputLabels, false)...)
}

return diagnostics
}
47 changes: 47 additions & 0 deletions internal/util/hcloudutil/labels_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package hcloudutil

import (
"context"
"testing"

"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stretchr/testify/assert"
)

func TestTerraformLabelsToHCloud(t *testing.T) {
tests := []struct {
name string
inputLabels types.Map
wantLabels *map[string]string
wantDiagnostics bool
}{
{
name: "Some Labels",
inputLabels: types.MapValueMust(types.StringType, map[string]attr.Value{"key1": types.StringValue("value1")}),
wantLabels: &map[string]string{"key1": "value1"},
wantDiagnostics: false,
},
{
name: "Empty Labels",
inputLabels: types.MapNull(types.StringType),
wantLabels: &map[string]string{},
wantDiagnostics: false,
},
{
name: "Invalid Map Labels",
inputLabels: types.MapValueMust(types.BoolType, map[string]attr.Value{"key1": types.BoolValue(true)}),
wantLabels: &map[string]string{},
wantDiagnostics: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var outputLabels map[string]string
diagnostics := TerraformLabelsToHCloud(context.Background(), tt.inputLabels, &outputLabels)
assert.Equalf(t, tt.wantDiagnostics, diagnostics != nil, "Unexpected Diagnostics: %v", diagnostics)
assert.Equalf(t, *tt.wantLabels, outputLabels, "Unexpected Labels")
})
}
}

0 comments on commit 7d8bf6e

Please sign in to comment.