github.com/hugorut/terraform@v1.1.3/src/backend/remote-state/etcdv3/backend_test.go (about) 1 package etcd 2 3 import ( 4 "context" 5 "fmt" 6 "os" 7 "reflect" 8 "strings" 9 "testing" 10 "time" 11 12 "github.com/hugorut/terraform/src/backend" 13 etcdv3 "go.etcd.io/etcd/clientv3" 14 ) 15 16 var ( 17 etcdv3Endpoints = strings.Split(os.Getenv("TF_ETCDV3_ENDPOINTS"), ",") 18 ) 19 20 const ( 21 keyPrefix = "tf-unit" 22 ) 23 24 func TestBackend_impl(t *testing.T) { 25 var _ backend.Backend = new(Backend) 26 } 27 28 func cleanupEtcdv3(t *testing.T) { 29 client, err := etcdv3.New(etcdv3.Config{ 30 Endpoints: etcdv3Endpoints, 31 }) 32 if err != nil { 33 t.Fatal(err) 34 } 35 36 res, err := client.KV.Delete(context.TODO(), keyPrefix, etcdv3.WithPrefix()) 37 if err != nil { 38 t.Fatal(err) 39 } 40 t.Logf("Cleaned up %d keys.", res.Deleted) 41 } 42 43 func prepareEtcdv3(t *testing.T) { 44 skip := os.Getenv("TF_ACC") == "" && os.Getenv("TF_ETCDV3_TEST") == "" 45 if skip { 46 t.Log("etcd server tests require setting TF_ACC or TF_ETCDV3_TEST") 47 t.Skip() 48 } 49 if reflect.DeepEqual(etcdv3Endpoints, []string{""}) { 50 t.Fatal("etcd server tests require setting TF_ETCDV3_ENDPOINTS") 51 } 52 cleanupEtcdv3(t) 53 } 54 55 func TestBackend(t *testing.T) { 56 prepareEtcdv3(t) 57 defer cleanupEtcdv3(t) 58 59 prefix := fmt.Sprintf("%s/%s/", keyPrefix, time.Now().Format(time.RFC3339)) 60 61 // Get the backend. We need two to test locking. 62 b1 := backend.TestBackendConfig(t, New(), backend.TestWrapConfig(map[string]interface{}{ 63 "endpoints": stringsToInterfaces(etcdv3Endpoints), 64 "prefix": prefix, 65 })) 66 67 b2 := backend.TestBackendConfig(t, New(), backend.TestWrapConfig(map[string]interface{}{ 68 "endpoints": stringsToInterfaces(etcdv3Endpoints), 69 "prefix": prefix, 70 })) 71 72 // Test 73 backend.TestBackendStates(t, b1) 74 backend.TestBackendStateLocks(t, b1, b2) 75 backend.TestBackendStateForceUnlock(t, b1, b2) 76 } 77 78 func TestBackend_lockDisabled(t *testing.T) { 79 prepareEtcdv3(t) 80 defer cleanupEtcdv3(t) 81 82 prefix := fmt.Sprintf("%s/%s/", keyPrefix, time.Now().Format(time.RFC3339)) 83 84 // Get the backend. We need two to test locking. 85 b1 := backend.TestBackendConfig(t, New(), backend.TestWrapConfig(map[string]interface{}{ 86 "endpoints": stringsToInterfaces(etcdv3Endpoints), 87 "prefix": prefix, 88 "lock": false, 89 })) 90 91 b2 := backend.TestBackendConfig(t, New(), backend.TestWrapConfig(map[string]interface{}{ 92 "endpoints": stringsToInterfaces(etcdv3Endpoints), 93 "prefix": prefix + "/" + "different", // Diff so locking test would fail if it was locking 94 "lock": false, 95 })) 96 97 // Test 98 backend.TestBackendStateLocks(t, b1, b2) 99 } 100 101 func stringsToInterfaces(strSlice []string) []interface{} { 102 var interfaceSlice []interface{} 103 for _, v := range strSlice { 104 interfaceSlice = append(interfaceSlice, v) 105 } 106 return interfaceSlice 107 }