move all remaining import_ tests into resource-specific tests (#2060)

I also did a bit of cleanup while I was here and noticed things that I thought could be improved in the files (wording changes, removing tests that aren't quite necessary, etc.) Take a look and make sure I didn't actually remove anything important!
This commit is contained in:
Dana Hoffman 2018-09-17 11:15:11 -07:00 committed by GitHub
parent 548f3685b1
commit cc98692acd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 269 additions and 1255 deletions

View File

@ -21,7 +21,6 @@ func TestAccDatasourceGoogleServiceAccount_basic(t *testing.T) {
{ {
Config: testAccCheckGoogleServiceAccount_basic(account), Config: testAccCheckGoogleServiceAccount_basic(account),
Check: resource.ComposeTestCheckFunc( Check: resource.ComposeTestCheckFunc(
testAccCheckGoogleServiceAccountExists(resourceName),
resource.TestCheckResourceAttr( resource.TestCheckResourceAttr(
resourceName, "id", fmt.Sprintf("projects/%s/serviceAccounts/%s@%s.iam.gserviceaccount.com", getTestProjectFromEnv(), account, getTestProjectFromEnv())), resourceName, "id", fmt.Sprintf("projects/%s/serviceAccounts/%s@%s.iam.gserviceaccount.com", getTestProjectFromEnv(), account, getTestProjectFromEnv())),
resource.TestCheckResourceAttrSet(resourceName, "email"), resource.TestCheckResourceAttrSet(resourceName, "email"),

View File

@ -1,57 +0,0 @@
package google
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccBigQueryDataset_importBasic(t *testing.T) {
t.Parallel()
resourceName := "google_bigquery_dataset.test"
datasetID := fmt.Sprintf("tf_test_%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckBigQueryDatasetDestroy,
Steps: []resource.TestStep{
{
Config: testAccBigQueryDataset(datasetID),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func TestAccBigQueryDataset_importAccess(t *testing.T) {
t.Parallel()
resourceName := "google_bigquery_dataset.access_test"
datasetID := fmt.Sprintf("tf_test_%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckBigQueryDatasetDestroy,
Steps: []resource.TestStep{
{
Config: testAccBigQueryDatasetWithTwoAccess(datasetID),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

View File

@ -1,34 +0,0 @@
package google
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccBigQueryTable_importBasic(t *testing.T) {
t.Parallel()
resourceName := "google_bigquery_table.test"
datasetID := fmt.Sprintf("tf_test_%s", acctest.RandString(10))
tableID := fmt.Sprintf("tf_test_%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckBigQueryTableDestroy,
Steps: []resource.TestStep{
{
Config: testAccBigQueryTable(datasetID, tableID),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

View File

@ -1,30 +0,0 @@
package google
import (
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccProjectIamCustomRole_import(t *testing.T) {
t.Parallel()
roleId := "tfIamRole" + acctest.RandString(10)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckGoogleProjectIamCustomRoleDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckGoogleProjectIamCustomRole_update(roleId),
},
{
ResourceName: "google_project_iam_custom_role.foo",
ImportState: true,
ImportStateVerify: true,
},
},
})
}

View File

@ -1,66 +0,0 @@
package google
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccServiceAccount_importBasic(t *testing.T) {
t.Parallel()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccServiceAccount_import("terraform-" + acctest.RandString(10)),
},
resource.TestStep{
ResourceName: "google_service_account.acceptance",
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func testAccServiceAccount_import(saName string) string {
return fmt.Sprintf(`
resource "google_service_account" "acceptance" {
account_id = "%s"
display_name = "%s"
}`, saName, saName)
}
func TestAccServiceAccount_importWithProject(t *testing.T) {
t.Parallel()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccServiceAccount_importWithProject(getTestProjectFromEnv(), "terraform-"+acctest.RandString(10)),
},
resource.TestStep{
ResourceName: "google_service_account.acceptance",
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func testAccServiceAccount_importWithProject(project, saName string) string {
return fmt.Sprintf(`
resource "google_service_account" "acceptance" {
project = "%s"
account_id = "%s"
display_name = "%s"
}`, project, saName, saName)
}

View File

@ -1,37 +0,0 @@
package google
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccKmsCryptoKey_importBasic(t *testing.T) {
t.Parallel()
resourceName := "google_kms_crypto_key.crypto_key"
projectId := "terraform-" + acctest.RandString(10)
projectOrg := getTestOrgFromEnv(t)
projectBillingAccount := getTestBillingAccountFromEnv(t)
keyRingName := fmt.Sprintf("tf-test-%s", acctest.RandString(10))
cryptoKeyName := fmt.Sprintf("tf-test-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testGoogleKmsCryptoKey_basic(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

View File

@ -1,34 +0,0 @@
package google
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccKmsKeyRing_importBasic(t *testing.T) {
resourceName := "google_kms_key_ring.key_ring"
projectId := "terraform-" + acctest.RandString(10)
projectOrg := getTestOrgFromEnv(t)
projectBillingAccount := getTestBillingAccountFromEnv(t)
keyRingName := fmt.Sprintf("tf-test-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testGoogleKmsKeyRing_basic(projectId, projectOrg, projectBillingAccount, keyRingName),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

View File

@ -1,31 +0,0 @@
package google
import (
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccLoggingProjectSink_importBasic(t *testing.T) {
t.Parallel()
sinkName := "tf-test-sink-" + acctest.RandString(10)
bucketName := "tf-test-sink-bucket-" + acctest.RandString(10)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccLoggingProjectSink_basic(sinkName, getTestProjectFromEnv(), bucketName),
},
resource.TestStep{
ResourceName: "google_logging_project_sink.basic",
ImportState: true,
ImportStateVerify: true,
},
},
})
}

View File

@ -1,61 +0,0 @@
package google
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccSpannerDatabase_importInstanceDatabase(t *testing.T) {
t.Parallel()
resourceName := "google_spanner_database.basic"
instanceName := fmt.Sprintf("span-iname-%s", acctest.RandString(10))
dbName := fmt.Sprintf("span-dbname-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckSpannerDatabaseDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccSpannerDatabase_basicImport(instanceName, dbName),
},
resource.TestStep{
ResourceName: resourceName,
ImportStateId: instanceName + "/" + dbName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func TestAccSpannerDatabase_importProjectInstanceDatabase(t *testing.T) {
t.Parallel()
resourceName := "google_spanner_database.basic"
instanceName := fmt.Sprintf("span-iname-%s", acctest.RandString(10))
dbName := fmt.Sprintf("span-dbname-%s", acctest.RandString(10))
projectId := getTestProjectFromEnv()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckSpannerDatabaseDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccSpannerDatabase_basicImportWithProject(projectId, instanceName, dbName),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

View File

@ -1,63 +0,0 @@
package google
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccSpannerInstance_importInstance(t *testing.T) {
t.Parallel()
resourceName := "google_spanner_instance.basic"
instanceName := fmt.Sprintf("span-itest-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckSpannerInstanceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccSpannerInstance_basic(instanceName),
},
resource.TestStep{
ResourceName: resourceName,
ImportStateId: instanceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func TestAccSpannerInstance_importProjectInstance(t *testing.T) {
t.Parallel()
resourceName := "google_spanner_instance.basic"
instanceName := fmt.Sprintf("span-itest-%s", acctest.RandString(10))
projectId := getTestProjectFromEnv()
if projectId == "" {
t.Skip("Unable to locate projectId via environment variables ... skipping ")
return
}
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckSpannerInstanceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccSpannerInstance_basicWithProject(projectId, instanceName),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

View File

@ -21,18 +21,19 @@ func TestAccBigQueryDataset_basic(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccBigQueryDataset(datasetID), Config: testAccBigQueryDataset(datasetID),
Check: resource.ComposeTestCheckFunc(
testAccCheckBigQueryDatasetExists(
"google_bigquery_dataset.test"),
),
}, },
{
ResourceName: "google_bigquery_dataset.test",
ImportState: true,
ImportStateVerify: true,
},
{ {
Config: testAccBigQueryDatasetUpdated(datasetID), Config: testAccBigQueryDatasetUpdated(datasetID),
Check: resource.ComposeTestCheckFunc( },
testAccCheckBigQueryDatasetExists( {
"google_bigquery_dataset.test"), ResourceName: "google_bigquery_dataset.test",
), ImportState: true,
ImportStateVerify: true,
}, },
}, },
}) })
@ -52,34 +53,35 @@ func TestAccBigQueryDataset_access(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccBigQueryDatasetWithOneAccess(datasetID), Config: testAccBigQueryDatasetWithOneAccess(datasetID),
Check: resource.ComposeTestCheckFunc(
testAccCheckBigQueryDatasetExists(
"google_bigquery_dataset.access_test"),
),
}, },
{
ResourceName: "google_bigquery_dataset.access_test",
ImportState: true,
ImportStateVerify: true,
},
{ {
Config: testAccBigQueryDatasetWithTwoAccess(datasetID), Config: testAccBigQueryDatasetWithTwoAccess(datasetID),
Check: resource.ComposeTestCheckFunc(
testAccCheckBigQueryDatasetExists(
"google_bigquery_dataset.access_test"),
),
}, },
{
ResourceName: "google_bigquery_dataset.access_test",
ImportState: true,
ImportStateVerify: true,
},
{ {
Config: testAccBigQueryDatasetWithOneAccess(datasetID), Config: testAccBigQueryDatasetWithOneAccess(datasetID),
Check: resource.ComposeTestCheckFunc(
testAccCheckBigQueryDatasetExists(
"google_bigquery_dataset.access_test"),
),
}, },
{
ResourceName: "google_bigquery_dataset.access_test",
ImportState: true,
ImportStateVerify: true,
},
{ {
Config: testAccBigQueryDatasetWithViewAccess(datasetID, otherDatasetID, otherTableID), Config: testAccBigQueryDatasetWithViewAccess(datasetID, otherDatasetID, otherTableID),
Check: resource.ComposeTestCheckFunc( },
testAccCheckBigQueryDatasetExists( {
"google_bigquery_dataset.access_test"), ResourceName: "google_bigquery_dataset.access_test",
), ImportState: true,
ImportStateVerify: true,
}, },
}, },
}) })
@ -102,32 +104,6 @@ func testAccCheckBigQueryDatasetDestroy(s *terraform.State) error {
return nil return nil
} }
func testAccCheckBigQueryDatasetExists(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}
config := testAccProvider.Meta().(*Config)
found, err := config.clientBigQuery.Datasets.Get(config.Project, rs.Primary.Attributes["dataset_id"]).Do()
if err != nil {
return err
}
if found.Id != rs.Primary.ID {
return fmt.Errorf("Dataset not found")
}
return nil
}
}
func testAccBigQueryDataset(datasetID string) string { func testAccBigQueryDataset(datasetID string) string {
return fmt.Sprintf(` return fmt.Sprintf(`
resource "google_bigquery_dataset" "test" { resource "google_bigquery_dataset" "test" {

View File

@ -2,7 +2,6 @@ package google
import ( import (
"fmt" "fmt"
"strings"
"testing" "testing"
"github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/acctest"
@ -13,7 +12,6 @@ import (
func TestAccBigQueryTable_Basic(t *testing.T) { func TestAccBigQueryTable_Basic(t *testing.T) {
t.Parallel() t.Parallel()
resourceName := "google_bigquery_table.test"
datasetID := fmt.Sprintf("tf_test_%s", acctest.RandString(10)) datasetID := fmt.Sprintf("tf_test_%s", acctest.RandString(10))
tableID := fmt.Sprintf("tf_test_%s", acctest.RandString(10)) tableID := fmt.Sprintf("tf_test_%s", acctest.RandString(10))
@ -24,20 +22,17 @@ func TestAccBigQueryTable_Basic(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccBigQueryTable(datasetID, tableID), Config: testAccBigQueryTable(datasetID, tableID),
Check: resource.ComposeTestCheckFunc(
testAccBigQueryTableExists(resourceName),
),
}, },
{
ResourceName: "google_bigquery_table.test",
ImportState: true,
ImportStateVerify: true,
},
{ {
Config: testAccBigQueryTableUpdated(datasetID, tableID), Config: testAccBigQueryTableUpdated(datasetID, tableID),
Check: resource.ComposeTestCheckFunc(
testAccBigQueryTableExists(resourceName),
),
}, },
{ {
ResourceName: resourceName, ResourceName: "google_bigquery_table.test",
ImportState: true, ImportState: true,
ImportStateVerify: true, ImportStateVerify: true,
}, },
@ -58,10 +53,11 @@ func TestAccBigQueryTable_View(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccBigQueryTableWithView(datasetID, tableID), Config: testAccBigQueryTableWithView(datasetID, tableID),
Check: resource.ComposeTestCheckFunc( },
testAccBigQueryTableExistsWithView( {
"google_bigquery_table.test"), ResourceName: "google_bigquery_table.test",
), ImportState: true,
ImportStateVerify: true,
}, },
}, },
}) })
@ -80,17 +76,19 @@ func TestAccBigQueryTable_ViewWithLegacySQL(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccBigQueryTableWithView(datasetID, tableID), Config: testAccBigQueryTableWithView(datasetID, tableID),
Check: resource.ComposeTestCheckFunc( },
testAccBigQueryTableExistsWithLegacySql( {
"google_bigquery_table.test", true), ResourceName: "google_bigquery_table.test",
), ImportState: true,
ImportStateVerify: true,
}, },
{ {
Config: testAccBigQueryTableWithNewSqlView(datasetID, tableID), Config: testAccBigQueryTableWithNewSqlView(datasetID, tableID),
Check: resource.ComposeTestCheckFunc( },
testAccBigQueryTableExistsWithLegacySql( {
"google_bigquery_table.test", false), ResourceName: "google_bigquery_table.test",
), ImportState: true,
ImportStateVerify: true,
}, },
}, },
}) })
@ -112,84 +110,6 @@ func testAccCheckBigQueryTableDestroy(s *terraform.State) error {
return nil return nil
} }
func testAccBigQueryTableExists(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}
config := testAccProvider.Meta().(*Config)
table, err := config.clientBigQuery.Tables.Get(config.Project, rs.Primary.Attributes["dataset_id"], rs.Primary.Attributes["table_id"]).Do()
if err != nil {
return fmt.Errorf("BigQuery Table not present")
}
if !strings.HasSuffix(table.Id, rs.Primary.Attributes["table_id"]) {
return fmt.Errorf("BigQuery Table ID does not match expected value")
}
return nil
}
}
func testAccBigQueryTableExistsWithView(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}
config := testAccProvider.Meta().(*Config)
table, err := config.clientBigQuery.Tables.Get(config.Project, rs.Primary.Attributes["dataset_id"], rs.Primary.Attributes["table_id"]).Do()
if err != nil {
return fmt.Errorf("BigQuery Table not present")
}
if table.View == nil {
return fmt.Errorf("View object missing on table")
}
return nil
}
}
func testAccBigQueryTableExistsWithLegacySql(n string, useLegacySql bool) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}
config := testAccProvider.Meta().(*Config)
table, err := config.clientBigQuery.Tables.Get(config.Project, rs.Primary.Attributes["dataset_id"], rs.Primary.Attributes["table_id"]).Do()
if err != nil {
return fmt.Errorf("BigQuery Table not present")
}
if table.View == nil {
return fmt.Errorf("View object missing on table")
}
if table.View.UseLegacySql != useLegacySql {
return fmt.Errorf("Value of UseLegacySQL does not match expected value")
}
return nil
}
}
func testAccBigQueryTable(datasetID, tableID string) string { func testAccBigQueryTable(datasetID, tableID string) string {
return fmt.Sprintf(` return fmt.Sprintf(`
resource "google_bigquery_dataset" "test" { resource "google_bigquery_dataset" "test" {

View File

@ -2,8 +2,6 @@ package google
import ( import (
"fmt" "fmt"
"reflect"
"sort"
"testing" "testing"
"github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/acctest"
@ -23,21 +21,20 @@ func TestAccProjectIamCustomRole_basic(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId), Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId),
Check: testAccCheckGoogleProjectIamCustomRole( Check: resource.TestCheckResourceAttr("google_project_iam_custom_role.foo", "stage", "GA"),
"google_project_iam_custom_role.foo", },
"My Custom Role", {
"foo", ResourceName: "google_project_iam_custom_role.foo",
"GA", ImportState: true,
[]string{"iam.roles.list"}), ImportStateVerify: true,
}, },
{ {
Config: testAccCheckGoogleProjectIamCustomRole_update(roleId), Config: testAccCheckGoogleProjectIamCustomRole_update(roleId),
Check: testAccCheckGoogleProjectIamCustomRole( },
"google_project_iam_custom_role.foo", {
"My Custom Role Updated", ResourceName: "google_project_iam_custom_role.foo",
"bar", ImportState: true,
"BETA", ImportStateVerify: true,
[]string{"iam.roles.list", "iam.roles.create", "iam.roles.delete"}),
}, },
}, },
}) })
@ -55,17 +52,32 @@ func TestAccProjectIamCustomRole_undelete(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId), Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId),
Check: testAccCheckGoogleProjectIamCustomRoleDeletionStatus("google_project_iam_custom_role.foo", false), Check: resource.TestCheckResourceAttr("google_project_iam_custom_role.foo", "deleted", "false"),
},
{
ResourceName: "google_project_iam_custom_role.foo",
ImportState: true,
ImportStateVerify: true,
}, },
// Soft-delete // Soft-delete
{ {
Config: testAccCheckGoogleProjectIamCustomRole_deleted(roleId), Config: testAccCheckGoogleProjectIamCustomRole_deleted(roleId),
Check: testAccCheckGoogleProjectIamCustomRoleDeletionStatus("google_project_iam_custom_role.foo", true), Check: resource.TestCheckResourceAttr("google_project_iam_custom_role.foo", "deleted", "true"),
},
{
ResourceName: "google_project_iam_custom_role.foo",
ImportState: true,
ImportStateVerify: true,
}, },
// Undelete // Undelete
{ {
Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId), Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId),
Check: testAccCheckGoogleProjectIamCustomRoleDeletionStatus("google_project_iam_custom_role.foo", false), Check: resource.TestCheckResourceAttr("google_project_iam_custom_role.foo", "deleted", "false"),
},
{
ResourceName: "google_project_iam_custom_role.foo",
ImportState: true,
ImportStateVerify: true,
}, },
}, },
}) })
@ -82,12 +94,11 @@ func TestAccProjectIamCustomRole_createAfterDestroy(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId), Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId),
Check: testAccCheckGoogleProjectIamCustomRole( },
"google_project_iam_custom_role.foo", {
"My Custom Role", ResourceName: "google_project_iam_custom_role.foo",
"foo", ImportState: true,
"GA", ImportStateVerify: true,
[]string{"iam.roles.list"}),
}, },
// Destroy resources // Destroy resources
{ {
@ -97,12 +108,11 @@ func TestAccProjectIamCustomRole_createAfterDestroy(t *testing.T) {
// Re-create with no existing state // Re-create with no existing state
{ {
Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId), Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId),
Check: testAccCheckGoogleProjectIamCustomRole( },
"google_project_iam_custom_role.foo", {
"My Custom Role", ResourceName: "google_project_iam_custom_role.foo",
"foo", ImportState: true,
"GA", ImportStateVerify: true,
[]string{"iam.roles.list"}),
}, },
}, },
}) })
@ -131,72 +141,6 @@ func testAccCheckGoogleProjectIamCustomRoleDestroy(s *terraform.State) error {
return nil return nil
} }
func testAccCheckGoogleProjectIamCustomRole(n, title, description, stage string, permissions []string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}
config := testAccProvider.Meta().(*Config)
role, err := config.clientIAM.Projects.Roles.Get(rs.Primary.ID).Do()
if err != nil {
return err
}
if title != role.Title {
return fmt.Errorf("Incorrect title. Expected %q, got %q", title, role.Title)
}
if description != role.Description {
return fmt.Errorf("Incorrect description. Expected %q, got %q", description, role.Description)
}
if stage != role.Stage {
return fmt.Errorf("Incorrect stage. Expected %q, got %q", stage, role.Stage)
}
sort.Strings(permissions)
sort.Strings(role.IncludedPermissions)
if !reflect.DeepEqual(permissions, role.IncludedPermissions) {
return fmt.Errorf("Incorrect permissions. Expected %q, got %q", permissions, role.IncludedPermissions)
}
return nil
}
}
func testAccCheckGoogleProjectIamCustomRoleDeletionStatus(n string, deleted bool) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}
config := testAccProvider.Meta().(*Config)
role, err := config.clientIAM.Projects.Roles.Get(rs.Primary.ID).Do()
if err != nil {
return err
}
if deleted != role.Deleted {
return fmt.Errorf("Incorrect deletion status. Expected %t, got %t", deleted, role.Deleted)
}
return nil
}
}
func testAccCheckGoogleProjectIamCustomRole_basic(roleId string) string { func testAccCheckGoogleProjectIamCustomRole_basic(roleId string) string {
return fmt.Sprintf(` return fmt.Sprintf(`
resource "google_project_iam_custom_role" "foo" { resource "google_project_iam_custom_role" "foo" {

View File

@ -26,33 +26,45 @@ func TestAccServiceAccount_basic(t *testing.T) {
resource.TestStep{ resource.TestStep{
Config: testAccServiceAccountBasic(accountId, displayName), Config: testAccServiceAccountBasic(accountId, displayName),
Check: resource.ComposeTestCheckFunc( Check: resource.ComposeTestCheckFunc(
testAccCheckGoogleServiceAccountExists("google_service_account.acceptance"),
resource.TestCheckResourceAttr( resource.TestCheckResourceAttr(
"google_service_account.acceptance", "project", project), "google_service_account.acceptance", "project", project),
), ),
}, },
resource.TestStep{
ResourceName: "google_service_account.acceptance",
ImportState: true,
ImportStateVerify: true,
},
// The second step updates the service account // The second step updates the service account
resource.TestStep{ resource.TestStep{
Config: testAccServiceAccountBasic(accountId, displayName2), Config: testAccServiceAccountBasic(accountId, displayName2),
Check: resource.ComposeTestCheckFunc( Check: resource.ComposeTestCheckFunc(
testAccCheckGoogleServiceAccountNameModified("google_service_account.acceptance", displayName2),
resource.TestCheckResourceAttr( resource.TestCheckResourceAttr(
"google_service_account.acceptance", "project", project), "google_service_account.acceptance", "project", project),
testAccStoreServiceAccountUniqueId(&uniqueId), testAccStoreServiceAccountUniqueId(&uniqueId),
), ),
}, },
resource.TestStep{
ResourceName: "google_service_account.acceptance",
ImportState: true,
ImportStateVerify: true,
},
// The third step explicitely adds the same default project to the service account configuration // The third step explicitely adds the same default project to the service account configuration
// and ensure the service account is not recreated by comparing the value of its unique_id with the one from the previous step // and ensure the service account is not recreated by comparing the value of its unique_id with the one from the previous step
resource.TestStep{ resource.TestStep{
Config: testAccServiceAccountWithProject(project, accountId, displayName2), Config: testAccServiceAccountWithProject(project, accountId, displayName2),
Check: resource.ComposeTestCheckFunc( Check: resource.ComposeTestCheckFunc(
testAccCheckGoogleServiceAccountNameModified("google_service_account.acceptance", displayName2),
resource.TestCheckResourceAttr( resource.TestCheckResourceAttr(
"google_service_account.acceptance", "project", project), "google_service_account.acceptance", "project", project),
resource.TestCheckResourceAttrPtr( resource.TestCheckResourceAttrPtr(
"google_service_account.acceptance", "unique_id", &uniqueId), "google_service_account.acceptance", "unique_id", &uniqueId),
), ),
}, },
resource.TestStep{
ResourceName: "google_service_account.acceptance",
ImportState: true,
ImportStateVerify: true,
},
}, },
}) })
} }
@ -75,6 +87,13 @@ func TestAccServiceAccount_createPolicy(t *testing.T) {
testAccCheckGoogleServiceAccountPolicyCount("google_service_account.acceptance", 1), testAccCheckGoogleServiceAccountPolicyCount("google_service_account.acceptance", 1),
), ),
}, },
resource.TestStep{
ResourceName: "google_service_account.acceptance",
ImportState: true,
ImportStateVerify: true,
// policy_data isn't a field on the service account object, and so isn't set in state.
ImportStateVerifyIgnore: []string{"policy_data"},
},
// The second step updates the service account with no IAM policy // The second step updates the service account with no IAM policy
resource.TestStep{ resource.TestStep{
Config: testAccServiceAccountBasic(accountId, displayName), Config: testAccServiceAccountBasic(accountId, displayName),
@ -82,6 +101,12 @@ func TestAccServiceAccount_createPolicy(t *testing.T) {
testAccCheckGoogleServiceAccountPolicyCount("google_service_account.acceptance", 0), testAccCheckGoogleServiceAccountPolicyCount("google_service_account.acceptance", 0),
), ),
}, },
resource.TestStep{
ResourceName: "google_service_account.acceptance",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"policy_data"},
},
// The final step re-applies the IAM policy // The final step re-applies the IAM policy
resource.TestStep{ resource.TestStep{
Config: testAccServiceAccountPolicy(accountId, getTestProjectFromEnv()), Config: testAccServiceAccountPolicy(accountId, getTestProjectFromEnv()),
@ -89,6 +114,12 @@ func TestAccServiceAccount_createPolicy(t *testing.T) {
testAccCheckGoogleServiceAccountPolicyCount("google_service_account.acceptance", 1), testAccCheckGoogleServiceAccountPolicyCount("google_service_account.acceptance", 1),
), ),
}, },
resource.TestStep{
ResourceName: "google_service_account.acceptance",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"policy_data"},
},
}, },
}) })
} }
@ -114,69 +145,40 @@ func testAccCheckGoogleServiceAccountPolicyCount(r string, n int) resource.TestC
} }
} }
func testAccCheckGoogleServiceAccountExists(r string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[r]
if !ok {
return fmt.Errorf("Not found: %s", r)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}
return nil
}
}
func testAccCheckGoogleServiceAccountNameModified(r, n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[r]
if !ok {
return fmt.Errorf("Not found: %s", r)
}
if rs.Primary.Attributes["display_name"] != n {
return fmt.Errorf("display_name is %q expected %q", rs.Primary.Attributes["display_name"], n)
}
return nil
}
}
func testAccServiceAccountBasic(account, name string) string { func testAccServiceAccountBasic(account, name string) string {
t := `resource "google_service_account" "acceptance" { return fmt.Sprintf(`
resource "google_service_account" "acceptance" {
account_id = "%v" account_id = "%v"
display_name = "%v" display_name = "%v"
}` }
return fmt.Sprintf(t, account, name) `, account, name)
} }
func testAccServiceAccountWithProject(project, account, name string) string { func testAccServiceAccountWithProject(project, account, name string) string {
t := `resource "google_service_account" "acceptance" { return fmt.Sprintf(`
resource "google_service_account" "acceptance" {
project = "%v" project = "%v"
account_id = "%v" account_id = "%v"
display_name = "%v" display_name = "%v"
}` }
return fmt.Sprintf(t, project, account, name) `, project, account, name)
} }
func testAccServiceAccountPolicy(account, project string) string { func testAccServiceAccountPolicy(account, project string) string {
return fmt.Sprintf(`
t := `resource "google_service_account" "acceptance" { resource "google_service_account" "acceptance" {
account_id = "%v" account_id = "%v"
display_name = "%v" display_name = "%v"
policy_data = "${data.google_iam_policy.service_account.policy_data}" policy_data = "${data.google_iam_policy.service_account.policy_data}"
} }
data "google_iam_policy" "service_account" { data "google_iam_policy" "service_account" {
binding { binding {
role = "roles/iam.serviceAccountActor" role = "roles/iam.serviceAccountActor"
members = [ members = [
"serviceAccount:%v@%v.iam.gserviceaccount.com", "serviceAccount:%v@%v.iam.gserviceaccount.com",
] ]
} }
}` }
`, account, account, account, project)
return fmt.Sprintf(t, account, account, account, project)
} }

View File

@ -2,7 +2,6 @@ package google
import ( import (
"fmt" "fmt"
"log"
"testing" "testing"
"time" "time"
@ -126,9 +125,11 @@ func TestAccKmsCryptoKey_basic(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
resource.TestStep{ resource.TestStep{
Config: testGoogleKmsCryptoKey_basic(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName), Config: testGoogleKmsCryptoKey_basic(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName),
Check: resource.ComposeTestCheckFunc( },
testAccCheckGoogleKmsCryptoKeyExists("google_kms_crypto_key.crypto_key"), resource.TestStep{
), ResourceName: "google_kms_crypto_key.crypto_key",
ImportState: true,
ImportStateVerify: true,
}, },
// Use a separate TestStep rather than a CheckDestroy because we need the project to still exist. // Use a separate TestStep rather than a CheckDestroy because we need the project to still exist.
resource.TestStep{ resource.TestStep{
@ -160,24 +161,27 @@ func TestAccKmsCryptoKey_rotation(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
resource.TestStep{ resource.TestStep{
Config: testGoogleKmsCryptoKey_rotation(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName, rotationPeriod), Config: testGoogleKmsCryptoKey_rotation(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName, rotationPeriod),
Check: resource.ComposeTestCheckFunc( },
testAccCheckGoogleKmsCryptoKeyExists("google_kms_crypto_key.crypto_key"), resource.TestStep{
testAccCheckGoogleKmsCryptoKeyHasRotationParams(rotationPeriod, "google_kms_crypto_key.crypto_key"), ResourceName: "google_kms_crypto_key.crypto_key",
), ImportState: true,
ImportStateVerify: true,
}, },
resource.TestStep{ resource.TestStep{
Config: testGoogleKmsCryptoKey_rotation(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName, updatedRotationPeriod), Config: testGoogleKmsCryptoKey_rotation(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName, updatedRotationPeriod),
Check: resource.ComposeTestCheckFunc( },
testAccCheckGoogleKmsCryptoKeyExists("google_kms_crypto_key.crypto_key"), resource.TestStep{
testAccCheckGoogleKmsCryptoKeyHasRotationParams(updatedRotationPeriod, "google_kms_crypto_key.crypto_key"), ResourceName: "google_kms_crypto_key.crypto_key",
), ImportState: true,
ImportStateVerify: true,
}, },
resource.TestStep{ resource.TestStep{
Config: testGoogleKmsCryptoKey_rotationRemoved(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName), Config: testGoogleKmsCryptoKey_rotationRemoved(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName),
Check: resource.ComposeTestCheckFunc( },
testAccCheckGoogleKmsCryptoKeyExists("google_kms_crypto_key.crypto_key"), resource.TestStep{
testAccCheckGoogleKmsCryptoKeyHasRotationParams("", "google_kms_crypto_key.crypto_key"), ResourceName: "google_kms_crypto_key.crypto_key",
), ImportState: true,
ImportStateVerify: true,
}, },
// Use a separate TestStep rather than a CheckDestroy because we need the project to still exist. // Use a separate TestStep rather than a CheckDestroy because we need the project to still exist.
resource.TestStep{ resource.TestStep{
@ -191,87 +195,6 @@ func TestAccKmsCryptoKey_rotation(t *testing.T) {
}) })
} }
func testAccCheckGoogleKmsCryptoKeyExists(resourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
config := testAccProvider.Meta().(*Config)
rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("Resource not found: %s", resourceName)
}
keyRingId, err := parseKmsKeyRingId(rs.Primary.Attributes["key_ring"], config)
if err != nil {
return err
}
cryptoKeyId := &kmsCryptoKeyId{
KeyRingId: *keyRingId,
Name: rs.Primary.Attributes["name"],
}
listCryptoKeysResponse, err := config.clientKms.Projects.Locations.KeyRings.CryptoKeys.List(cryptoKeyId.parentId()).Do()
if err != nil {
return fmt.Errorf("Error listing KeyRings: %s", err)
}
for _, cryptoKey := range listCryptoKeysResponse.CryptoKeys {
log.Printf("[DEBUG] Found CryptoKey: %s", cryptoKey.Name)
if cryptoKey.Name == cryptoKeyId.cryptoKeyId() {
return nil
}
}
return fmt.Errorf("CryptoKey not found: %s", cryptoKeyId.cryptoKeyId())
}
}
func testAccCheckGoogleKmsCryptoKeyHasRotationParams(rotationPeriod, resourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
config := testAccProvider.Meta().(*Config)
rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("Resource not found: %s", resourceName)
}
keyRingId, err := parseKmsKeyRingId(rs.Primary.Attributes["key_ring"], config)
if err != nil {
return err
}
cryptoKeyId := &kmsCryptoKeyId{
KeyRingId: *keyRingId,
Name: rs.Primary.Attributes["name"],
}
getCryptoKeyResponse, err := config.clientKms.Projects.Locations.KeyRings.CryptoKeys.Get(cryptoKeyId.cryptoKeyId()).Do()
if err != nil {
return err
}
if rotationPeriod != getCryptoKeyResponse.RotationPeriod {
return fmt.Errorf("Expected rotation period %s to match input %s", getCryptoKeyResponse.RotationPeriod, rotationPeriod)
}
if getCryptoKeyResponse.NextRotationTime == "" {
return nil
}
_, err = time.Parse(time.RFC3339Nano, getCryptoKeyResponse.NextRotationTime)
if err != nil {
return fmt.Errorf("Failed to parse NextRotationTime timestamp: %s", err)
}
return nil
}
}
/* /*
KMS KeyRings cannot be deleted. This ensures that the CryptoKey resource was removed from state, KMS KeyRings cannot be deleted. This ensures that the CryptoKey resource was removed from state,
even though the server-side resource was not removed. even though the server-side resource was not removed.

View File

@ -2,7 +2,6 @@ package google
import ( import (
"fmt" "fmt"
"log"
"testing" "testing"
"github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/acctest"
@ -85,9 +84,11 @@ func TestAccKmsKeyRing_basic(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
resource.TestStep{ resource.TestStep{
Config: testGoogleKmsKeyRing_basic(projectId, projectOrg, projectBillingAccount, keyRingName), Config: testGoogleKmsKeyRing_basic(projectId, projectOrg, projectBillingAccount, keyRingName),
Check: resource.ComposeTestCheckFunc( },
testAccCheckGoogleKmsKeyRingExists("google_kms_key_ring.key_ring"), resource.TestStep{
), ResourceName: "google_kms_key_ring.key_ring",
ImportState: true,
ImportStateVerify: true,
}, },
resource.TestStep{ resource.TestStep{
Config: testGoogleKmsKeyRing_removed(projectId, projectOrg, projectBillingAccount), Config: testGoogleKmsKeyRing_removed(projectId, projectOrg, projectBillingAccount),
@ -99,38 +100,6 @@ func TestAccKmsKeyRing_basic(t *testing.T) {
}) })
} }
func testAccCheckGoogleKmsKeyRingExists(resourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
config := testAccProvider.Meta().(*Config)
rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("Resource not found: %s", resourceName)
}
keyRingId := &kmsKeyRingId{
Project: rs.Primary.Attributes["project"],
Location: rs.Primary.Attributes["location"],
Name: rs.Primary.Attributes["name"],
}
listKeyRingsResponse, err := config.clientKms.Projects.Locations.KeyRings.List(keyRingId.parentId()).Do()
if err != nil {
return fmt.Errorf("Error listing KeyRings: %s", err)
}
for _, keyRing := range listKeyRingsResponse.KeyRings {
log.Printf("[DEBUG] Found KeyRing: %s", keyRing.Name)
if keyRing.Name == keyRingId.keyRingId() {
return nil
}
}
return fmt.Errorf("KeyRing not found: %s", keyRingId.keyRingId())
}
}
/* /*
KMS KeyRings cannot be deleted. This ensures that the KeyRing resource was removed from state, KMS KeyRings cannot be deleted. This ensures that the KeyRing resource was removed from state,
even though the server-side resource was not removed. even though the server-side resource was not removed.

View File

@ -2,13 +2,11 @@ package google
import ( import (
"fmt" "fmt"
"strconv"
"testing" "testing"
"github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" "github.com/hashicorp/terraform/terraform"
"google.golang.org/api/logging/v2"
) )
func TestAccLoggingProjectSink_basic(t *testing.T) { func TestAccLoggingProjectSink_basic(t *testing.T) {
@ -17,8 +15,6 @@ func TestAccLoggingProjectSink_basic(t *testing.T) {
sinkName := "tf-test-sink-" + acctest.RandString(10) sinkName := "tf-test-sink-" + acctest.RandString(10)
bucketName := "tf-test-sink-bucket-" + acctest.RandString(10) bucketName := "tf-test-sink-bucket-" + acctest.RandString(10)
var sink logging.LogSink
resource.Test(t, resource.TestCase{ resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, Providers: testAccProviders,
@ -26,34 +22,11 @@ func TestAccLoggingProjectSink_basic(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccLoggingProjectSink_basic(sinkName, getTestProjectFromEnv(), bucketName), Config: testAccLoggingProjectSink_basic(sinkName, getTestProjectFromEnv(), bucketName),
Check: resource.ComposeTestCheckFunc(
testAccCheckLoggingProjectSinkExists("google_logging_project_sink.basic", &sink),
testAccCheckLoggingProjectSink(&sink, "google_logging_project_sink.basic"),
),
}, },
},
})
}
func TestAccLoggingProjectSink_uniqueWriter(t *testing.T) {
t.Parallel()
sinkName := "tf-test-sink-" + acctest.RandString(10)
bucketName := "tf-test-sink-bucket-" + acctest.RandString(10)
var sink logging.LogSink
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckLoggingProjectSinkDestroy,
Steps: []resource.TestStep{
{ {
Config: testAccLoggingProjectSink_uniqueWriter(sinkName, bucketName), ResourceName: "google_logging_project_sink.basic",
Check: resource.ComposeTestCheckFunc( ImportState: true,
testAccCheckLoggingProjectSinkExists("google_logging_project_sink.unique_writer", &sink), ImportStateVerify: true,
testAccCheckLoggingProjectSink(&sink, "google_logging_project_sink.unique_writer"),
),
}, },
}, },
}) })
@ -66,8 +39,6 @@ func TestAccLoggingProjectSink_updatePreservesUniqueWriter(t *testing.T) {
bucketName := "tf-test-sink-bucket-" + acctest.RandString(10) bucketName := "tf-test-sink-bucket-" + acctest.RandString(10)
updatedBucketName := "tf-test-sink-bucket-" + acctest.RandString(10) updatedBucketName := "tf-test-sink-bucket-" + acctest.RandString(10)
var sinkBefore, sinkAfter logging.LogSink
resource.Test(t, resource.TestCase{ resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, Providers: testAccProviders,
@ -75,31 +46,22 @@ func TestAccLoggingProjectSink_updatePreservesUniqueWriter(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccLoggingProjectSink_uniqueWriter(sinkName, bucketName), Config: testAccLoggingProjectSink_uniqueWriter(sinkName, bucketName),
Check: resource.ComposeTestCheckFunc( },
testAccCheckLoggingProjectSinkExists("google_logging_project_sink.unique_writer", &sinkBefore), {
testAccCheckLoggingProjectSink(&sinkBefore, "google_logging_project_sink.unique_writer"), ResourceName: "google_logging_project_sink.unique_writer",
), ImportState: true,
}, { ImportStateVerify: true,
},
{
Config: testAccLoggingProjectSink_uniqueWriterUpdated(sinkName, updatedBucketName), Config: testAccLoggingProjectSink_uniqueWriterUpdated(sinkName, updatedBucketName),
Check: resource.ComposeTestCheckFunc( },
testAccCheckLoggingProjectSinkExists("google_logging_project_sink.unique_writer", &sinkAfter), {
testAccCheckLoggingProjectSink(&sinkAfter, "google_logging_project_sink.unique_writer"), ResourceName: "google_logging_project_sink.unique_writer",
), ImportState: true,
ImportStateVerify: true,
}, },
}, },
}) })
// Destination and Filter should have changed, but WriterIdentity should be the same
if sinkBefore.Destination == sinkAfter.Destination {
t.Errorf("Expected Destination to change, but it didn't: Destination = %#v", sinkBefore.Destination)
}
if sinkBefore.Filter == sinkAfter.Filter {
t.Errorf("Expected Filter to change, but it didn't: Filter = %#v", sinkBefore.Filter)
}
if sinkBefore.WriterIdentity != sinkAfter.WriterIdentity {
t.Errorf("Expected WriterIdentity to be the same, but it differs: before = %#v, after = %#v",
sinkBefore.WriterIdentity, sinkAfter.WriterIdentity)
}
} }
func TestAccLoggingProjectSink_heredoc(t *testing.T) { func TestAccLoggingProjectSink_heredoc(t *testing.T) {
@ -108,8 +70,6 @@ func TestAccLoggingProjectSink_heredoc(t *testing.T) {
sinkName := "tf-test-sink-" + acctest.RandString(10) sinkName := "tf-test-sink-" + acctest.RandString(10)
bucketName := "tf-test-sink-bucket-" + acctest.RandString(10) bucketName := "tf-test-sink-bucket-" + acctest.RandString(10)
var sink logging.LogSink
resource.Test(t, resource.TestCase{ resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, Providers: testAccProviders,
@ -117,11 +77,8 @@ func TestAccLoggingProjectSink_heredoc(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccLoggingProjectSink_heredoc(sinkName, getTestProjectFromEnv(), bucketName), Config: testAccLoggingProjectSink_heredoc(sinkName, getTestProjectFromEnv(), bucketName),
Check: resource.ComposeTestCheckFunc( },
testAccCheckLoggingProjectSinkExists("google_logging_project_sink.heredoc", &sink), {
testAccCheckLoggingProjectSink(&sink, "google_logging_project_sink.heredoc"),
),
}, {
ResourceName: "google_logging_project_sink.heredoc", ResourceName: "google_logging_project_sink.heredoc",
ImportState: true, ImportState: true,
ImportStateVerify: true, ImportStateVerify: true,
@ -149,113 +106,74 @@ func testAccCheckLoggingProjectSinkDestroy(s *terraform.State) error {
return nil return nil
} }
func testAccCheckLoggingProjectSinkExists(n string, sink *logging.LogSink) resource.TestCheckFunc {
return func(s *terraform.State) error {
attributes, err := getResourceAttributes(n, s)
if err != nil {
return err
}
config := testAccProvider.Meta().(*Config)
si, err := config.clientLogging.Projects.Sinks.Get(attributes["id"]).Do()
if err != nil {
return err
}
*sink = *si
return nil
}
}
func testAccCheckLoggingProjectSink(sink *logging.LogSink, n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
attributes, err := getResourceAttributes(n, s)
if err != nil {
return err
}
if sink.Destination != attributes["destination"] {
return fmt.Errorf("mismatch on destination: api has %s but client has %s", sink.Destination, attributes["destination"])
}
if sink.Filter != attributes["filter"] {
return fmt.Errorf("mismatch on filter: api has %s but client has %s", sink.Filter, attributes["filter"])
}
apiLooksUnique := strconv.FormatBool(nonUniqueWriterAccount != attributes["writer_identity"])
if apiLooksUnique != attributes["unique_writer_identity"] {
return fmt.Errorf("mismatch on unique_writer_identity: api looks like %s but client has %s", apiLooksUnique, attributes["unique_writer_identity"])
}
if sink.WriterIdentity != attributes["writer_identity"] {
return fmt.Errorf("mismatch on writer_identity: api has %s but client has %s", sink.WriterIdentity, attributes["writer_identity"])
}
return nil
}
}
func testAccLoggingProjectSink_basic(name, project, bucketName string) string { func testAccLoggingProjectSink_basic(name, project, bucketName string) string {
return fmt.Sprintf(` return fmt.Sprintf(`
resource "google_logging_project_sink" "basic" { resource "google_logging_project_sink" "basic" {
name = "%s" name = "%s"
project = "%s" project = "%s"
destination = "storage.googleapis.com/${google_storage_bucket.log-bucket.name}" destination = "storage.googleapis.com/${google_storage_bucket.log-bucket.name}"
filter = "logName=\"projects/%s/logs/compute.googleapis.com%%2Factivity_log\" AND severity>=ERROR" filter = "logName=\"projects/%s/logs/compute.googleapis.com%%2Factivity_log\" AND severity>=ERROR"
unique_writer_identity = false unique_writer_identity = false
} }
resource "google_storage_bucket" "log-bucket" { resource "google_storage_bucket" "log-bucket" {
name = "%s" name = "%s"
}`, name, project, project, bucketName) }
`, name, project, project, bucketName)
} }
func testAccLoggingProjectSink_uniqueWriter(name, bucketName string) string { func testAccLoggingProjectSink_uniqueWriter(name, bucketName string) string {
return fmt.Sprintf(` return fmt.Sprintf(`
resource "google_logging_project_sink" "unique_writer" { resource "google_logging_project_sink" "unique_writer" {
name = "%s" name = "%s"
destination = "storage.googleapis.com/${google_storage_bucket.log-bucket.name}" destination = "storage.googleapis.com/${google_storage_bucket.log-bucket.name}"
filter = "logName=\"projects/%s/logs/compute.googleapis.com%%2Factivity_log\" AND severity>=ERROR" filter = "logName=\"projects/%s/logs/compute.googleapis.com%%2Factivity_log\" AND severity>=ERROR"
unique_writer_identity = true unique_writer_identity = true
} }
resource "google_storage_bucket" "log-bucket" { resource "google_storage_bucket" "log-bucket" {
name = "%s" name = "%s"
}`, name, getTestProjectFromEnv(), bucketName) }
`, name, getTestProjectFromEnv(), bucketName)
} }
func testAccLoggingProjectSink_uniqueWriterUpdated(name, bucketName string) string { func testAccLoggingProjectSink_uniqueWriterUpdated(name, bucketName string) string {
return fmt.Sprintf(` return fmt.Sprintf(`
resource "google_logging_project_sink" "unique_writer" { resource "google_logging_project_sink" "unique_writer" {
name = "%s" name = "%s"
destination = "storage.googleapis.com/${google_storage_bucket.log-bucket.name}" destination = "storage.googleapis.com/${google_storage_bucket.log-bucket.name}"
filter = "logName=\"projects/%s/logs/compute.googleapis.com%%2Factivity_log\" AND severity>=WARNING" filter = "logName=\"projects/%s/logs/compute.googleapis.com%%2Factivity_log\" AND severity>=WARNING"
unique_writer_identity = true unique_writer_identity = true
} }
resource "google_storage_bucket" "log-bucket" { resource "google_storage_bucket" "log-bucket" {
name = "%s" name = "%s"
}`, name, getTestProjectFromEnv(), bucketName) }
`, name, getTestProjectFromEnv(), bucketName)
} }
func testAccLoggingProjectSink_heredoc(name, project, bucketName string) string { func testAccLoggingProjectSink_heredoc(name, project, bucketName string) string {
return fmt.Sprintf(` return fmt.Sprintf(`
resource "google_logging_project_sink" "heredoc" { resource "google_logging_project_sink" "heredoc" {
name = "%s" name = "%s"
project = "%s" project = "%s"
destination = "storage.googleapis.com/${google_storage_bucket.log-bucket.name}" destination = "storage.googleapis.com/${google_storage_bucket.log-bucket.name}"
filter = <<EOS filter = <<EOS
logName="projects/%s/logs/compute.googleapis.com%%2Factivity_log" logName="projects/%s/logs/compute.googleapis.com%%2Factivity_log"
AND severity>=ERROR AND severity>=ERROR
EOS
EOS
unique_writer_identity = false unique_writer_identity = false
} }
resource "google_storage_bucket" "log-bucket" { resource "google_storage_bucket" "log-bucket" {
name = "%s" name = "%s"
}`, name, project, project, bucketName) }
`, name, project, project, bucketName)
} }

View File

@ -3,16 +3,15 @@ package google
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"regexp"
"strings" "strings"
"testing" "testing"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" "github.com/hashicorp/terraform/terraform"
"google.golang.org/api/googleapi" "google.golang.org/api/googleapi"
"google.golang.org/api/spanner/v1"
) )
// Unit Tests // Unit Tests
@ -118,24 +117,23 @@ func expectInvalidSpannerDbImportId(t *testing.T, id *spannerDatabaseId, e error
func TestAccSpannerDatabase_basic(t *testing.T) { func TestAccSpannerDatabase_basic(t *testing.T) {
t.Parallel() t.Parallel()
var db spanner.Database
rnd := acctest.RandString(10) rnd := acctest.RandString(10)
resource.Test(t, resource.TestCase{ resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, Providers: testAccProviders,
CheckDestroy: resource.ComposeTestCheckFunc( CheckDestroy: testAccCheckSpannerDatabaseDestroy,
testAccCheckSpannerInstanceDestroy,
testAccCheckSpannerDatabaseDestroy),
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccSpannerDatabase_basic(rnd), Config: testAccSpannerDatabase_basic(rnd),
Check: resource.ComposeTestCheckFunc( Check: resource.ComposeTestCheckFunc(
testAccCheckSpannerDatabaseExists("google_spanner_database.basic", &db),
resource.TestCheckResourceAttr("google_spanner_database.basic", "name", "my-db-"+rnd),
resource.TestCheckResourceAttrSet("google_spanner_database.basic", "state"), resource.TestCheckResourceAttrSet("google_spanner_database.basic", "state"),
), ),
}, },
{
ResourceName: "google_spanner_database.basic",
ImportState: true,
ImportStateVerify: true,
},
}, },
}) })
} }
@ -143,48 +141,23 @@ func TestAccSpannerDatabase_basic(t *testing.T) {
func TestAccSpannerDatabase_basicWithInitialDDL(t *testing.T) { func TestAccSpannerDatabase_basicWithInitialDDL(t *testing.T) {
t.Parallel() t.Parallel()
var db spanner.Database
rnd := acctest.RandString(10) rnd := acctest.RandString(10)
resource.Test(t, resource.TestCase{ resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, Providers: testAccProviders,
CheckDestroy: resource.ComposeTestCheckFunc( CheckDestroy: testAccCheckSpannerDatabaseDestroy,
testAccCheckSpannerInstanceDestroy,
testAccCheckSpannerDatabaseDestroy),
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccSpannerDatabase_basicWithInitialDDL(rnd), Config: testAccSpannerDatabase_basicWithInitialDDL(rnd),
Check: resource.ComposeTestCheckFunc(
testAccCheckSpannerDatabaseExists("google_spanner_database.basic", &db),
),
},
},
})
}
func TestAccSpannerDatabase_duplicateNameError(t *testing.T) {
t.Parallel()
var db spanner.Database
rnd := acctest.RandString(10)
dbName := fmt.Sprintf("spanner-test-%s", rnd)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: resource.ComposeTestCheckFunc(
testAccCheckSpannerInstanceDestroy,
testAccCheckSpannerDatabaseDestroy),
Steps: []resource.TestStep{
{
Config: testAccSpannerDatabase_duplicateNameError_part1(rnd, dbName),
Check: resource.ComposeTestCheckFunc(
testAccCheckSpannerDatabaseExists("google_spanner_database.basic1", &db),
),
}, },
{ {
Config: testAccSpannerDatabase_duplicateNameError_part2(rnd, dbName), ResourceName: "google_spanner_database.basic",
ExpectError: regexp.MustCompile( ImportState: true,
fmt.Sprintf(".*A database with name %s already exists", dbName)), ImportStateVerify: true,
// DDL statements get issued at the time the create/update
// occurs, which means storing them in state isn't really
// necessary.
ImportStateVerifyIgnore: []string{"ddl"},
}, },
}, },
}) })
@ -215,47 +188,19 @@ func testAccCheckSpannerDatabaseDestroy(s *terraform.State) error {
_, err = config.clientSpanner.Projects.Instances.Databases.Get( _, err = config.clientSpanner.Projects.Instances.Databases.Get(
id.databaseUri()).Do() id.databaseUri()).Do()
if err != nil { if err == nil {
if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == http.StatusNotFound { return fmt.Errorf("Spanner database still exists")
return nil
}
return fmt.Errorf("Error make GCP platform call to verify spanner database deleted: %s", err.Error())
} }
return fmt.Errorf("Spanner database not destroyed - still exists")
if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == http.StatusNotFound {
return nil
}
return errwrap.Wrapf("Error verifying spanner database deleted: {{err}}", err)
} }
return nil return nil
} }
func testAccCheckSpannerDatabaseExists(n string, instance *spanner.Database) resource.TestCheckFunc {
return func(s *terraform.State) error {
config := testAccProvider.Meta().(*Config)
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Terraform resource Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set for Spanner instance")
}
id, err := extractSpannerDatabaseId(rs.Primary.ID)
found, err := config.clientSpanner.Projects.Instances.Databases.Get(
id.databaseUri()).Do()
if err != nil {
return err
}
if fName := GetResourceNameFromSelfLink(found.Name); fName != id.Database {
return fmt.Errorf("Spanner database %s not found, found %s instead", id.Database, fName)
}
*instance = *found
return nil
}
}
func testAccSpannerDatabase_basic(rnd string) string { func testAccSpannerDatabase_basic(rnd string) string {
return fmt.Sprintf(` return fmt.Sprintf(`
resource "google_spanner_instance" "basic" { resource "google_spanner_instance" "basic" {
@ -268,7 +213,6 @@ resource "google_spanner_instance" "basic" {
resource "google_spanner_database" "basic" { resource "google_spanner_database" "basic" {
instance = "${google_spanner_instance.basic.name}" instance = "${google_spanner_instance.basic.name}"
name = "my-db-%s" name = "my-db-%s"
} }
`, rnd, rnd, rnd) `, rnd, rnd, rnd)
} }
@ -291,67 +235,3 @@ resource "google_spanner_database" "basic" {
} }
`, rnd, rnd, rnd) `, rnd, rnd, rnd)
} }
func testAccSpannerDatabase_duplicateNameError_part1(rnd, dbName string) string {
return fmt.Sprintf(`
resource "google_spanner_instance" "basic" {
name = "my-instance-%s"
config = "regional-us-central1"
display_name = "my-displayname-%s"
num_nodes = 1
}
resource "google_spanner_database" "basic1" {
instance = "${google_spanner_instance.basic.name}"
name = "%s"
}
`, rnd, rnd, dbName)
}
func testAccSpannerDatabase_duplicateNameError_part2(rnd, dbName string) string {
return fmt.Sprintf(`
%s
resource "google_spanner_database" "basic2" {
instance = "${google_spanner_instance.basic.name}"
name = "%s"
}
`, testAccSpannerDatabase_duplicateNameError_part1(rnd, dbName), dbName)
}
func testAccSpannerDatabase_basicImport(iname, dbname string) string {
return fmt.Sprintf(`
resource "google_spanner_instance" "basic" {
name = "%s"
config = "regional-us-central1"
display_name = "%s"
num_nodes = 1
}
resource "google_spanner_database" "basic" {
instance = "${google_spanner_instance.basic.name}"
name = "%s"
}
`, iname, iname, dbname)
}
func testAccSpannerDatabase_basicImportWithProject(project, iname, dbname string) string {
return fmt.Sprintf(`
resource "google_spanner_instance" "basic" {
project = "%s"
name = "%s"
config = "regional-us-central1"
display_name = "%s"
num_nodes = 1
}
resource "google_spanner_database" "basic" {
project = "%s"
instance = "${google_spanner_instance.basic.name}"
name = "%s"
}
`, project, iname, iname, project, dbname)
}

View File

@ -3,16 +3,16 @@ package google
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"regexp"
"testing" "testing"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" "github.com/hashicorp/terraform/terraform"
"google.golang.org/api/googleapi"
"google.golang.org/api/spanner/v1"
"strings" "strings"
"google.golang.org/api/googleapi"
) )
// Unit Tests // Unit Tests
@ -147,9 +147,7 @@ func expectEquals(t *testing.T, expected, actual string) {
func TestAccSpannerInstance_basic(t *testing.T) { func TestAccSpannerInstance_basic(t *testing.T) {
t.Parallel() t.Parallel()
var instance spanner.Instance idName := fmt.Sprintf("spanner-test-%s", acctest.RandString(10))
rnd := acctest.RandString(10)
idName := fmt.Sprintf("spanner-test-%s", rnd)
resource.Test(t, resource.TestCase{ resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, Providers: testAccProviders,
@ -158,14 +156,14 @@ func TestAccSpannerInstance_basic(t *testing.T) {
{ {
Config: testAccSpannerInstance_basic(idName), Config: testAccSpannerInstance_basic(idName),
Check: resource.ComposeTestCheckFunc( Check: resource.ComposeTestCheckFunc(
testAccCheckSpannerInstanceExists("google_spanner_instance.basic", &instance),
resource.TestCheckResourceAttr("google_spanner_instance.basic", "name", idName),
resource.TestCheckResourceAttr("google_spanner_instance.basic", "display_name", idName+"-dname"),
resource.TestCheckResourceAttr("google_spanner_instance.basic", "num_nodes", "1"),
resource.TestCheckResourceAttrSet("google_spanner_instance.basic", "state"), resource.TestCheckResourceAttrSet("google_spanner_instance.basic", "state"),
), ),
}, },
{
ResourceName: "google_spanner_instance.basic",
ImportState: true,
ImportStateVerify: true,
},
}, },
}) })
} }
@ -173,9 +171,7 @@ func TestAccSpannerInstance_basic(t *testing.T) {
func TestAccSpannerInstance_basicWithAutogenName(t *testing.T) { func TestAccSpannerInstance_basicWithAutogenName(t *testing.T) {
t.Parallel() t.Parallel()
var instance spanner.Instance displayName := fmt.Sprintf("spanner-test-%s-dname", acctest.RandString(10))
rnd := acctest.RandString(10)
displayName := fmt.Sprintf("spanner-test-%s-dname", rnd)
resource.Test(t, resource.TestCase{ resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, Providers: testAccProviders,
@ -184,37 +180,13 @@ func TestAccSpannerInstance_basicWithAutogenName(t *testing.T) {
{ {
Config: testAccSpannerInstance_basicWithAutogenName(displayName), Config: testAccSpannerInstance_basicWithAutogenName(displayName),
Check: resource.ComposeTestCheckFunc( Check: resource.ComposeTestCheckFunc(
testAccCheckSpannerInstanceExists("google_spanner_instance.basic", &instance),
resource.TestCheckResourceAttr("google_spanner_instance.basic", "display_name", displayName),
resource.TestCheckResourceAttrSet("google_spanner_instance.basic", "name"), resource.TestCheckResourceAttrSet("google_spanner_instance.basic", "name"),
), ),
}, },
},
})
}
func TestAccSpannerInstance_duplicateNameError(t *testing.T) {
t.Parallel()
var instance spanner.Instance
rnd := acctest.RandString(10)
idName := fmt.Sprintf("spanner-test-%s", rnd)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckSpannerInstanceDestroy,
Steps: []resource.TestStep{
{ {
Config: testAccSpannerInstance_duplicateNameError_part1(idName), ResourceName: "google_spanner_instance.basic",
Check: resource.ComposeTestCheckFunc( ImportState: true,
testAccCheckSpannerInstanceExists("google_spanner_instance.basic1", &instance), ImportStateVerify: true,
),
},
{
Config: testAccSpannerInstance_duplicateNameError_part2(idName),
ExpectError: regexp.MustCompile(
fmt.Sprintf("Error, the name %s is not unique within project", idName)),
}, },
}, },
}) })
@ -223,10 +195,8 @@ func TestAccSpannerInstance_duplicateNameError(t *testing.T) {
func TestAccSpannerInstance_update(t *testing.T) { func TestAccSpannerInstance_update(t *testing.T) {
t.Parallel() t.Parallel()
var instance spanner.Instance dName1 := fmt.Sprintf("spanner-dname1-%s", acctest.RandString(10))
rnd := acctest.RandString(10) dName2 := fmt.Sprintf("spanner-dname2-%s", acctest.RandString(10))
dName1 := fmt.Sprintf("spanner-dname1-%s", rnd)
dName2 := fmt.Sprintf("spanner-dname2-%s", rnd)
resource.Test(t, resource.TestCase{ resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, Providers: testAccProviders,
@ -234,21 +204,19 @@ func TestAccSpannerInstance_update(t *testing.T) {
Steps: []resource.TestStep{ Steps: []resource.TestStep{
{ {
Config: testAccSpannerInstance_update(dName1, 1, false), Config: testAccSpannerInstance_update(dName1, 1, false),
Check: resource.ComposeTestCheckFunc( },
testAccCheckSpannerInstanceExists("google_spanner_instance.updater", &instance), {
resource.TestCheckResourceAttr("google_spanner_instance.updater", "display_name", dName1), ResourceName: "google_spanner_instance.updater",
resource.TestCheckResourceAttr("google_spanner_instance.updater", "num_nodes", "1"), ImportState: true,
resource.TestCheckResourceAttr("google_spanner_instance.updater", "labels.%", "1"), ImportStateVerify: true,
),
}, },
{ {
Config: testAccSpannerInstance_update(dName2, 2, true), Config: testAccSpannerInstance_update(dName2, 2, true),
Check: resource.ComposeTestCheckFunc( },
testAccCheckSpannerInstanceExists("google_spanner_instance.updater", &instance), {
resource.TestCheckResourceAttr("google_spanner_instance.updater", "display_name", dName2), ResourceName: "google_spanner_instance.updater",
resource.TestCheckResourceAttr("google_spanner_instance.updater", "num_nodes", "2"), ImportState: true,
resource.TestCheckResourceAttr("google_spanner_instance.updater", "labels.%", "2"), ImportStateVerify: true,
),
}, },
}, },
}) })
@ -279,52 +247,19 @@ func testAccCheckSpannerInstanceDestroy(s *terraform.State) error {
_, err = config.clientSpanner.Projects.Instances.Get( _, err = config.clientSpanner.Projects.Instances.Get(
id.instanceUri()).Do() id.instanceUri()).Do()
if err != nil { if err == nil {
if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == http.StatusNotFound { return fmt.Errorf("Spanner instance still exists")
return nil
}
return fmt.Errorf("Error make GCP platform call to verify spanner instance deleted: %s", err.Error())
} }
return fmt.Errorf("Spanner instance not destroyed - still exists")
if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == http.StatusNotFound {
return nil
}
return errwrap.Wrapf("Error verifying spanner instance deleted: {{err}}", err)
} }
return nil return nil
} }
func testAccCheckSpannerInstanceExists(n string, instance *spanner.Instance) resource.TestCheckFunc {
return func(s *terraform.State) error {
config := testAccProvider.Meta().(*Config)
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Terraform resource Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set for Spanner instance")
}
id, err := extractSpannerInstanceId(rs.Primary.ID)
if err != nil {
return err
}
found, err := config.clientSpanner.Projects.Instances.Get(
id.instanceUri()).Do()
if err != nil {
return err
}
fName := GetResourceNameFromSelfLink(found.Name)
if fName != GetResourceNameFromSelfLink(rs.Primary.ID) {
return fmt.Errorf("Spanner instance %s not found, found %s instead", rs.Primary.ID, fName)
}
*instance = *found
return nil
}
}
func testAccSpannerInstance_basic(name string) string { func testAccSpannerInstance_basic(name string) string {
return fmt.Sprintf(` return fmt.Sprintf(`
resource "google_spanner_instance" "basic" { resource "google_spanner_instance" "basic" {
@ -336,18 +271,6 @@ resource "google_spanner_instance" "basic" {
`, name, name) `, name, name)
} }
func testAccSpannerInstance_basicWithProject(project, name string) string {
return fmt.Sprintf(`
resource "google_spanner_instance" "basic" {
project = "%s"
name = "%s"
config = "regional-us-central1"
display_name = "%s-dname"
num_nodes = 1
}
`, project, name, name)
}
func testAccSpannerInstance_basicWithAutogenName(name string) string { func testAccSpannerInstance_basicWithAutogenName(name string) string {
return fmt.Sprintf(` return fmt.Sprintf(`
resource "google_spanner_instance" "basic" { resource "google_spanner_instance" "basic" {
@ -358,33 +281,7 @@ resource "google_spanner_instance" "basic" {
`, name) `, name)
} }
func testAccSpannerInstance_duplicateNameError_part1(name string) string {
return fmt.Sprintf(`
resource "google_spanner_instance" "basic1" {
name = "%s"
config = "regional-us-central1"
display_name = "%s-dname"
num_nodes = 1
}
`, name, name)
}
func testAccSpannerInstance_duplicateNameError_part2(name string) string {
return fmt.Sprintf(`
%s
resource "google_spanner_instance" "basic2" {
name = "%s"
config = "regional-us-central1"
display_name = "%s-dname"
num_nodes = 1
}
`, testAccSpannerInstance_duplicateNameError_part1(name), name, name)
}
func testAccSpannerInstance_update(name string, nodes int, addLabel bool) string { func testAccSpannerInstance_update(name string, nodes int, addLabel bool) string {
extraLabel := "" extraLabel := ""
if addLabel { if addLabel {
extraLabel = "\"key2\" = \"value2\"" extraLabel = "\"key2\" = \"value2\""

View File

@ -565,7 +565,6 @@ func TestAccStorageBucket_encryption(t *testing.T) {
resource.TestStep{ resource.TestStep{
Config: testAccStorageBucket_encryption(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName, bucketName), Config: testAccStorageBucket_encryption(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName, bucketName),
Check: resource.ComposeTestCheckFunc( Check: resource.ComposeTestCheckFunc(
testAccCheckGoogleKmsCryptoKeyExists("google_kms_crypto_key.crypto_key"),
testAccCheckStorageBucketExists( testAccCheckStorageBucketExists(
"google_storage_bucket.bucket", bucketName, &bucket), "google_storage_bucket.bucket", bucketName, &bucket),
), ),