Skip to content

Commit 7d8bf6e

Browse files
authored
chore: utility to convert labels to hcloud-go types (#892)
We often have to convert between the Terraform Plugin Framework and hcloud-go representations for labels. Will be used by #817
1 parent 68e366e commit 7d8bf6e

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

internal/util/hcloudutil/labels.go

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package hcloudutil
2+
3+
import (
4+
"context"
5+
6+
"github.com/hashicorp/terraform-plugin-framework/diag"
7+
"github.com/hashicorp/terraform-plugin-framework/types"
8+
)
9+
10+
func TerraformLabelsToHCloud(ctx context.Context, inputLabels types.Map, outputLabels *map[string]string) diag.Diagnostics {
11+
var diagnostics diag.Diagnostics
12+
*outputLabels = make(map[string]string, len(inputLabels.Elements()))
13+
14+
if !inputLabels.IsNull() {
15+
diagnostics.Append(inputLabels.ElementsAs(ctx, outputLabels, false)...)
16+
}
17+
18+
return diagnostics
19+
}
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package hcloudutil
2+
3+
import (
4+
"context"
5+
"testing"
6+
7+
"github.com/hashicorp/terraform-plugin-framework/attr"
8+
"github.com/hashicorp/terraform-plugin-framework/types"
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
func TestTerraformLabelsToHCloud(t *testing.T) {
13+
tests := []struct {
14+
name string
15+
inputLabels types.Map
16+
wantLabels *map[string]string
17+
wantDiagnostics bool
18+
}{
19+
{
20+
name: "Some Labels",
21+
inputLabels: types.MapValueMust(types.StringType, map[string]attr.Value{"key1": types.StringValue("value1")}),
22+
wantLabels: &map[string]string{"key1": "value1"},
23+
wantDiagnostics: false,
24+
},
25+
{
26+
name: "Empty Labels",
27+
inputLabels: types.MapNull(types.StringType),
28+
wantLabels: &map[string]string{},
29+
wantDiagnostics: false,
30+
},
31+
{
32+
name: "Invalid Map Labels",
33+
inputLabels: types.MapValueMust(types.BoolType, map[string]attr.Value{"key1": types.BoolValue(true)}),
34+
wantLabels: &map[string]string{},
35+
wantDiagnostics: true,
36+
},
37+
}
38+
39+
for _, tt := range tests {
40+
t.Run(tt.name, func(t *testing.T) {
41+
var outputLabels map[string]string
42+
diagnostics := TerraformLabelsToHCloud(context.Background(), tt.inputLabels, &outputLabels)
43+
assert.Equalf(t, tt.wantDiagnostics, diagnostics != nil, "Unexpected Diagnostics: %v", diagnostics)
44+
assert.Equalf(t, *tt.wantLabels, outputLabels, "Unexpected Labels")
45+
})
46+
}
47+
}

0 commit comments

Comments
 (0)