github.com/graywolf-at-work-2/terraform-vendor@v1.4.5/internal/backend/remote-state/oss/backend_test.go (about)

     1  package oss
     2  
     3  import (
     4  	"fmt"
     5  	"math/rand"
     6  	"os"
     7  	"testing"
     8  	"time"
     9  
    10  	"strings"
    11  
    12  	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    13  	"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
    14  	"github.com/hashicorp/terraform/internal/backend"
    15  	"github.com/hashicorp/terraform/internal/configs/hcl2shim"
    16  )
    17  
    18  // verify that we are doing ACC tests or the OSS tests specifically
    19  func testACC(t *testing.T) {
    20  	skip := os.Getenv("TF_ACC") == "" && os.Getenv("TF_OSS_TEST") == ""
    21  	if skip {
    22  		t.Log("oss backend tests require setting TF_ACC or TF_OSS_TEST")
    23  		t.Skip()
    24  	}
    25  	if skip {
    26  		t.Fatal("oss backend tests require setting ALICLOUD_ACCESS_KEY or ALICLOUD_ACCESS_KEY_ID")
    27  	}
    28  	if os.Getenv("ALICLOUD_REGION") == "" {
    29  		os.Setenv("ALICLOUD_REGION", "cn-beijing")
    30  	}
    31  }
    32  
    33  func TestBackend_impl(t *testing.T) {
    34  	var _ backend.Backend = new(Backend)
    35  }
    36  
    37  func TestBackendConfig(t *testing.T) {
    38  	testACC(t)
    39  	config := map[string]interface{}{
    40  		"region":              "cn-beijing",
    41  		"bucket":              "terraform-backend-oss-test",
    42  		"prefix":              "mystate",
    43  		"key":                 "first.tfstate",
    44  		"tablestore_endpoint": "https://terraformstate.cn-beijing.ots.aliyuncs.com",
    45  		"tablestore_table":    "TableStore",
    46  	}
    47  
    48  	b := backend.TestBackendConfig(t, New(), backend.TestWrapConfig(config)).(*Backend)
    49  
    50  	if !strings.HasPrefix(b.ossClient.Config.Endpoint, "https://oss-cn-beijing") {
    51  		t.Fatalf("Incorrect region was provided")
    52  	}
    53  	if b.bucketName != "terraform-backend-oss-test" {
    54  		t.Fatalf("Incorrect bucketName was provided")
    55  	}
    56  	if b.statePrefix != "mystate" {
    57  		t.Fatalf("Incorrect state file path was provided")
    58  	}
    59  	if b.stateKey != "first.tfstate" {
    60  		t.Fatalf("Incorrect keyName was provided")
    61  	}
    62  
    63  	if b.ossClient.Config.AccessKeyID == "" {
    64  		t.Fatalf("No Access Key Id was provided")
    65  	}
    66  	if b.ossClient.Config.AccessKeySecret == "" {
    67  		t.Fatalf("No Secret Access Key was provided")
    68  	}
    69  }
    70  
    71  func TestBackendConfigWorkSpace(t *testing.T) {
    72  	testACC(t)
    73  	bucketName := fmt.Sprintf("terraform-backend-oss-test-%d", rand.Intn(1000))
    74  	config := map[string]interface{}{
    75  		"region":              "cn-beijing",
    76  		"bucket":              bucketName,
    77  		"prefix":              "mystate",
    78  		"key":                 "first.tfstate",
    79  		"tablestore_endpoint": "https://terraformstate.cn-beijing.ots.aliyuncs.com",
    80  		"tablestore_table":    "TableStore",
    81  	}
    82  
    83  	b := backend.TestBackendConfig(t, New(), backend.TestWrapConfig(config)).(*Backend)
    84  	createOSSBucket(t, b.ossClient, bucketName)
    85  	defer deleteOSSBucket(t, b.ossClient, bucketName)
    86  	if _, err := b.Workspaces(); err != nil {
    87  		t.Fatal(err.Error())
    88  	}
    89  	if !strings.HasPrefix(b.ossClient.Config.Endpoint, "https://oss-cn-beijing") {
    90  		t.Fatalf("Incorrect region was provided")
    91  	}
    92  	if b.bucketName != bucketName {
    93  		t.Fatalf("Incorrect bucketName was provided")
    94  	}
    95  	if b.statePrefix != "mystate" {
    96  		t.Fatalf("Incorrect state file path was provided")
    97  	}
    98  	if b.stateKey != "first.tfstate" {
    99  		t.Fatalf("Incorrect keyName was provided")
   100  	}
   101  
   102  	if b.ossClient.Config.AccessKeyID == "" {
   103  		t.Fatalf("No Access Key Id was provided")
   104  	}
   105  	if b.ossClient.Config.AccessKeySecret == "" {
   106  		t.Fatalf("No Secret Access Key was provided")
   107  	}
   108  }
   109  
   110  func TestBackendConfigProfile(t *testing.T) {
   111  	testACC(t)
   112  	config := map[string]interface{}{
   113  		"region":              "cn-beijing",
   114  		"bucket":              "terraform-backend-oss-test",
   115  		"prefix":              "mystate",
   116  		"key":                 "first.tfstate",
   117  		"tablestore_endpoint": "https://terraformstate.cn-beijing.ots.aliyuncs.com",
   118  		"tablestore_table":    "TableStore",
   119  		"profile":             "default",
   120  	}
   121  
   122  	b := backend.TestBackendConfig(t, New(), backend.TestWrapConfig(config)).(*Backend)
   123  
   124  	if !strings.HasPrefix(b.ossClient.Config.Endpoint, "https://oss-cn-beijing") {
   125  		t.Fatalf("Incorrect region was provided")
   126  	}
   127  	if b.bucketName != "terraform-backend-oss-test" {
   128  		t.Fatalf("Incorrect bucketName was provided")
   129  	}
   130  	if b.statePrefix != "mystate" {
   131  		t.Fatalf("Incorrect state file path was provided")
   132  	}
   133  	if b.stateKey != "first.tfstate" {
   134  		t.Fatalf("Incorrect keyName was provided")
   135  	}
   136  
   137  	if b.ossClient.Config.AccessKeyID == "" {
   138  		t.Fatalf("No Access Key Id was provided")
   139  	}
   140  	if b.ossClient.Config.AccessKeySecret == "" {
   141  		t.Fatalf("No Secret Access Key was provided")
   142  	}
   143  }
   144  
   145  func TestBackendConfig_invalidKey(t *testing.T) {
   146  	testACC(t)
   147  	cfg := hcl2shim.HCL2ValueFromConfigValue(map[string]interface{}{
   148  		"region":              "cn-beijing",
   149  		"bucket":              "terraform-backend-oss-test",
   150  		"prefix":              "/leading-slash",
   151  		"name":                "/test.tfstate",
   152  		"tablestore_endpoint": "https://terraformstate.cn-beijing.ots.aliyuncs.com",
   153  		"tablestore_table":    "TableStore",
   154  	})
   155  
   156  	_, results := New().PrepareConfig(cfg)
   157  	if !results.HasErrors() {
   158  		t.Fatal("expected config validation error")
   159  	}
   160  }
   161  
   162  func TestBackend(t *testing.T) {
   163  	testACC(t)
   164  
   165  	bucketName := fmt.Sprintf("terraform-remote-oss-test-%x", time.Now().Unix())
   166  	statePrefix := "multi/level/path/"
   167  
   168  	b1 := backend.TestBackendConfig(t, New(), backend.TestWrapConfig(map[string]interface{}{
   169  		"bucket": bucketName,
   170  		"prefix": statePrefix,
   171  	})).(*Backend)
   172  
   173  	b2 := backend.TestBackendConfig(t, New(), backend.TestWrapConfig(map[string]interface{}{
   174  		"bucket": bucketName,
   175  		"prefix": statePrefix,
   176  	})).(*Backend)
   177  
   178  	createOSSBucket(t, b1.ossClient, bucketName)
   179  	defer deleteOSSBucket(t, b1.ossClient, bucketName)
   180  
   181  	backend.TestBackendStates(t, b1)
   182  	backend.TestBackendStateLocks(t, b1, b2)
   183  	backend.TestBackendStateForceUnlock(t, b1, b2)
   184  }
   185  
   186  func createOSSBucket(t *testing.T, ossClient *oss.Client, bucketName string) {
   187  	// Be clear about what we're doing in case the user needs to clean this up later.
   188  	if err := ossClient.CreateBucket(bucketName); err != nil {
   189  		t.Fatal("failed to create test OSS bucket:", err)
   190  	}
   191  }
   192  
   193  func deleteOSSBucket(t *testing.T, ossClient *oss.Client, bucketName string) {
   194  	warning := "WARNING: Failed to delete the test OSS bucket. It may have been left in your Alibaba Cloud account and may incur storage charges. (error was %s)"
   195  
   196  	// first we have to get rid of the env objects, or we can't delete the bucket
   197  	bucket, err := ossClient.Bucket(bucketName)
   198  	if err != nil {
   199  		t.Fatal("Error getting bucket:", err)
   200  		return
   201  	}
   202  	objects, err := bucket.ListObjects()
   203  	if err != nil {
   204  		t.Logf(warning, err)
   205  		return
   206  	}
   207  	for _, obj := range objects.Objects {
   208  		if err := bucket.DeleteObject(obj.Key); err != nil {
   209  			// this will need cleanup no matter what, so just warn and exit
   210  			t.Logf(warning, err)
   211  			return
   212  		}
   213  	}
   214  
   215  	if err := ossClient.DeleteBucket(bucketName); err != nil {
   216  		t.Logf(warning, err)
   217  	}
   218  }
   219  
   220  // create the tablestore table, and wait until we can query it.
   221  func createTablestoreTable(t *testing.T, otsClient *tablestore.TableStoreClient, tableName string) {
   222  	tableMeta := new(tablestore.TableMeta)
   223  	tableMeta.TableName = tableName
   224  	tableMeta.AddPrimaryKeyColumn(pkName, tablestore.PrimaryKeyType_STRING)
   225  
   226  	tableOption := new(tablestore.TableOption)
   227  	tableOption.TimeToAlive = -1
   228  	tableOption.MaxVersion = 1
   229  
   230  	reservedThroughput := new(tablestore.ReservedThroughput)
   231  
   232  	_, err := otsClient.CreateTable(&tablestore.CreateTableRequest{
   233  		TableMeta:          tableMeta,
   234  		TableOption:        tableOption,
   235  		ReservedThroughput: reservedThroughput,
   236  	})
   237  	if err != nil {
   238  		t.Fatal(err)
   239  	}
   240  }
   241  
   242  func deleteTablestoreTable(t *testing.T, otsClient *tablestore.TableStoreClient, tableName string) {
   243  	params := &tablestore.DeleteTableRequest{
   244  		TableName: tableName,
   245  	}
   246  	_, err := otsClient.DeleteTable(params)
   247  	if err != nil {
   248  		t.Logf("WARNING: Failed to delete the test TableStore table %q. It has been left in your Alibaba Cloud account and may incur charges. (error was %s)", tableName, err)
   249  	}
   250  }