forked from IvanOfThings/terraform-provider-clickhouse
/
testutils.go
84 lines (69 loc) · 2.59 KB
/
testutils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package testutils
import (
"fmt"
"strconv"
"testing"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"github.com/Triple-Whale/terraform-provider-clickhouse/v4/pkg/provider"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
var TestAccProviders map[string]*schema.Provider
var TestAccProvider *schema.Provider
func init() {
TestAccProvider = provider.New("dev")()
TestAccProviders = map[string]*schema.Provider{
"clickhouse": TestAccProvider,
}
}
func Provider() map[string]*schema.Provider {
return TestAccProviders
}
func TestAccPreCheck(t *testing.T) {
// You can add code here to run prior to any test case execution, for example assertions
// about the appropriate environment variables being set are common to see in a pre-check
// function.
}
//func ClickhouseProviderFactory() (*schema.Provider, error) {
// TestAccProvider = provider.New("dev")()
// return TestAccProvider, nil
//}
//
//func GetProviderFactories() map[string]func() (*schema.Provider, error) {
// return map[string]func() (*schema.Provider, error){"clickhouse": ClickhouseProviderFactory}
//}
func getSetFromSetStateAttribute(attributes map[string]string, key string) (*schema.Set, error) {
itemsLength, err := strconv.Atoi(attributes[fmt.Sprintf("%s.#", key)])
if err != nil {
return nil, err
}
var items []interface{}
for i := 0; i < itemsLength; i++ {
items = append(items, attributes[fmt.Sprintf("%s.%d", key, i)])
}
if len(items) != itemsLength {
return nil, fmt.Errorf("%s.# mismatch items retrieved from state", key)
}
return schema.NewSet(schema.HashString, items), nil
}
// Elements of lists and sets are stored in terraform state as independent variables with the sufix "_{index}".
// To check the value, we need to get the length of the list and iterate over it and get the list elements one by one
// and compare them with the values from the current test plan.
func CheckStateSetAttr(attrKey string, resource string, expectedItems []string) resource.TestCheckFunc {
return func(state *terraform.State) error {
attributes := state.RootModule().Resources[resource].Primary.Attributes
set, err := getSetFromSetStateAttribute(attributes, attrKey)
if err != nil {
return fmt.Errorf("get %s set: %v", attrKey, err)
}
if len(expectedItems) != set.Len() {
return fmt.Errorf("expectedItems length mismatching between plan and state")
}
for _, expectedItem := range expectedItems {
if set.Contains(expectedItem) == false {
return fmt.Errorf("expectedItem %s not found in state", expectedItem)
}
}
return nil
}
}