Skip to content

Commit

Permalink
chore: Unifies SDK connection getting in tests (#1864)
Browse files Browse the repository at this point in the history
* Conn an ConnV2 functions

* muxedProviderFactoryFn doesn't need to be exported

* acc.MongoDBClient

* ignore "updated" filelds in flaky tests that sometimes expected and got differ in a second.

example:

 error=
  | ImportStateVerify attributes not equivalent. Difference is shown below. The - symbol indicates attributes missing after import.
  |
  | \u00a0\u00a0map[string]string{
  | -\u00a0\t"updated": "2024-01-23T01:33:43Z",
  | +\u00a0\t"updated": "2024-01-23T01:33:42Z",
  | \u00a0\u00a0}

* apply feedback: remove muxedProviderFactoryFn
  • Loading branch information
lantoli committed Jan 23, 2024
1 parent 4e56b98 commit c58ff01
Show file tree
Hide file tree
Showing 76 changed files with 142 additions and 786 deletions.
26 changes: 7 additions & 19 deletions internal/provider/provider.go
Expand Up @@ -21,7 +21,6 @@ import (
"github.com/hashicorp/terraform-plugin-go/tfprotov6"
"github.com/hashicorp/terraform-plugin-mux/tf5to6server"
"github.com/hashicorp/terraform-plugin-mux/tf6muxserver"
sdkv2schema "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"

"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/validate"
Expand Down Expand Up @@ -451,28 +450,17 @@ func NewFrameworkProvider() provider.Provider {
}

func MuxedProviderFactory() func() tfprotov6.ProviderServer {
return MuxedProviderFactoryFn(NewSdkV2Provider())
}

// MuxedProviderFactoryFn creates mux provider using existing sdk v2 provider passed as parameter and creating new instance of framework provider.
// Used in testing where existing sdk v2 provider has to be used.
func MuxedProviderFactoryFn(sdkV2Provider *sdkv2schema.Provider) func() tfprotov6.ProviderServer {
fwProvider := NewFrameworkProvider()

v2Provider := NewSdkV2Provider()
newProvider := NewFrameworkProvider()
ctx := context.Background()
upgradedSdkProvider, err := tf5to6server.UpgradeServer(ctx, sdkV2Provider.GRPCProvider)
upgradedSdkProvider, err := tf5to6server.UpgradeServer(ctx, v2Provider.GRPCProvider)
if err != nil {
log.Fatal(err)
}

providers := []func() tfprotov6.ProviderServer{
func() tfprotov6.ProviderServer {
return upgradedSdkProvider
},
providerserver.NewProtocol6(fwProvider),
}

muxServer, err := tf6muxserver.NewMuxServer(ctx, providers...)
muxServer, err := tf6muxserver.NewMuxServer(ctx,
func() tfprotov6.ProviderServer { return upgradedSdkProvider },
providerserver.NewProtocol6(newProvider),
)
if err != nil {
log.Fatal(err)
}
Expand Down
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
)

Expand Down Expand Up @@ -116,20 +115,15 @@ func TestAccProjectRSAccessListAPIKey_importBasic(t *testing.T) {

func testAccCheckMongoDBAtlasAccessListAPIKeyExists(resourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := acc.TestAccProviderSdkV2.Meta().(*config.MongoDBClient).Atlas

rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("not found: %s", resourceName)
}

if rs.Primary.ID == "" {
return fmt.Errorf("no ID is set")
}

ids := conversion.DecodeStateID(rs.Primary.ID)

_, _, err := conn.AccessListAPIKeys.Get(context.Background(), ids["org_id"], ids["api_key_id"], ids["entry"])
_, _, err := acc.Conn().AccessListAPIKeys.Get(context.Background(), ids["org_id"], ids["api_key_id"], ids["entry"])
if err != nil {
return fmt.Errorf("access list API Key (%s) does not exist", ids["api_key_id"])
}
Expand All @@ -139,16 +133,12 @@ func testAccCheckMongoDBAtlasAccessListAPIKeyExists(resourceName string) resourc
}

func testAccCheckMongoDBAtlasAccessListAPIKeyDestroy(s *terraform.State) error {
conn := acc.TestAccProviderSdkV2.Meta().(*config.MongoDBClient).Atlas

for _, rs := range s.RootModule().Resources {
if rs.Type != "mongodbatlas_access_list_api_key" {
continue
}

ids := conversion.DecodeStateID(rs.Primary.ID)

_, _, err := conn.AccessListAPIKeys.Get(context.Background(), ids["project_id"], ids["api_key_id"], ids["entry"])
_, _, err := acc.Conn().AccessListAPIKeys.Get(context.Background(), ids["project_id"], ids["api_key_id"], ids["entry"])
if err == nil {
return fmt.Errorf("access list API Key (%s) still exists", ids["api_key_id"])
}
Expand Down
Expand Up @@ -12,7 +12,6 @@ import (
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
"github.com/mwielbut/pointy"
matlas "go.mongodb.org/atlas/mongodbatlas"
Expand Down Expand Up @@ -681,26 +680,19 @@ func TestAccClusterAdvancedCluster_WithTags(t *testing.T) {

func testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName string, cluster *matlas.AdvancedCluster) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := acc.TestMongoDBClient.(*config.MongoDBClient).Atlas

rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("not found: %s", resourceName)
}

if rs.Primary.ID == "" {
return fmt.Errorf("no ID is set")
}

ids := conversion.DecodeStateID(rs.Primary.ID)

log.Printf("[DEBUG] projectID: %s, name %s", ids["project_id"], ids["cluster_name"])

if clusterResp, _, err := conn.AdvancedClusters.Get(context.Background(), ids["project_id"], ids["cluster_name"]); err == nil {
if clusterResp, _, err := acc.Conn().AdvancedClusters.Get(context.Background(), ids["project_id"], ids["cluster_name"]); err == nil {
*cluster = *clusterResp
return nil
}

return fmt.Errorf("cluster(%s:%s) does not exist", rs.Primary.Attributes["project_id"], rs.Primary.ID)
}
}
Expand Down
Expand Up @@ -13,7 +13,6 @@ import (
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
matlas "go.mongodb.org/atlas/mongodbatlas"
)
Expand Down Expand Up @@ -153,21 +152,17 @@ func configTotalCount(orgID, projectName string) string {

func checkCount(resourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := acc.TestAccProviderSdkV2.Meta().(*config.MongoDBClient).Atlas

rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("not found: %s", resourceName)
}

if rs.Primary.ID == "" {
return fmt.Errorf("no ID is set")
}

ids := conversion.DecodeStateID(rs.Primary.ID)
projectID := ids["project_id"]

alertResp, _, err := conn.AlertConfigurations.List(context.Background(), projectID, &matlas.ListOptions{
alertResp, _, err := acc.Conn().AlertConfigurations.List(context.Background(), projectID, &matlas.ListOptions{
PageNum: 0,
ItemsPerPage: 100,
IncludeCount: true,
Expand Down
Expand Up @@ -11,7 +11,6 @@ import (
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/service/alertconfiguration"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
"go.mongodb.org/atlas-sdk/v20231115004/admin"
Expand Down Expand Up @@ -311,7 +310,7 @@ func TestAccConfigRSAlertConfiguration_importBasic(t *testing.T) {
ImportStateIdFunc: importStateProjectIDFunc(resourceName),
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"project_id"},
ImportStateVerifyIgnore: []string{"project_id", "updated"},
},
},
})
Expand Down Expand Up @@ -362,7 +361,7 @@ func TestAccConfigRSAlertConfiguration_importConfigNotifications(t *testing.T) {
ImportStateIdFunc: importStateProjectIDFunc(resourceName),
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"project_id"},
ImportStateVerifyIgnore: []string{"project_id", "updated"},
},
},
})
Expand Down Expand Up @@ -399,7 +398,7 @@ func TestAccConfigRSAlertConfiguration_importPagerDuty(t *testing.T) {
ImportStateIdFunc: importStateProjectIDFunc(resourceName),
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"notification.0.service_key"}, // service key is not returned by api in import operation
ImportStateVerifyIgnore: []string{"updated", "notification.0.service_key"}, // service key is not returned by api in import operation
},
},
})
Expand Down Expand Up @@ -544,46 +543,34 @@ func TestAccConfigRSAlertConfiguration_withVictorOps(t *testing.T) {

func checkExists(resourceName string, alert *admin.GroupAlertsConfig) resource.TestCheckFunc {
return func(s *terraform.State) error {
connV2 := acc.TestMongoDBClient.(*config.MongoDBClient).AtlasV2

rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("not found: %s", resourceName)
}

if rs.Primary.ID == "" {
return fmt.Errorf("no ID is set")
}

ids := conversion.DecodeStateID(rs.Primary.ID)

alertResp, _, err := connV2.AlertConfigurationsApi.GetAlertConfiguration(context.Background(), ids[alertconfiguration.EncodedIDKeyProjectID], ids[alertconfiguration.EncodedIDKeyAlertID]).Execute()
alertResp, _, err := acc.ConnV2().AlertConfigurationsApi.GetAlertConfiguration(context.Background(), ids[alertconfiguration.EncodedIDKeyProjectID], ids[alertconfiguration.EncodedIDKeyAlertID]).Execute()
if err != nil {
return fmt.Errorf("the Alert Configuration(%s) does not exist", ids[alertconfiguration.EncodedIDKeyAlertID])
}

alert = alertResp

return nil
}
}

func checkDestroy(s *terraform.State) error {
conn := acc.TestMongoDBClient.(*config.MongoDBClient).Atlas

for _, rs := range s.RootModule().Resources {
if rs.Type != "mongodbatlas_alert_configuration" {
continue
}

ids := conversion.DecodeStateID(rs.Primary.ID)

alert, _, err := conn.AlertConfigurations.GetAnAlertConfig(context.Background(), ids[alertconfiguration.EncodedIDKeyProjectID], ids[alertconfiguration.EncodedIDKeyAlertID])
alert, _, err := acc.Conn().AlertConfigurations.GetAnAlertConfig(context.Background(), ids[alertconfiguration.EncodedIDKeyProjectID], ids[alertconfiguration.EncodedIDKeyAlertID])
if alert != nil {
return fmt.Errorf("the Project Alert Configuration(%s) still exists %s", ids[alertconfiguration.EncodedIDKeyAlertID], err)
}
}

return nil
}

Expand All @@ -593,7 +580,6 @@ func importStateProjectIDFunc(resourceName string) resource.ImportStateIdFunc {
if !ok {
return "", fmt.Errorf("not found: %s", resourceName)
}

return fmt.Sprintf("%s-%s", rs.Primary.Attributes["project_id"], rs.Primary.Attributes["alert_configuration_id"]), nil
}
}
Expand Down
16 changes: 2 additions & 14 deletions internal/service/apikey/resource_api_key_test.go
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
)

Expand Down Expand Up @@ -81,44 +80,33 @@ func TestAccConfigRSAPIKey_importBasic(t *testing.T) {

func testAccCheckMongoDBAtlasAPIKeyExists(resourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := acc.TestAccProviderSdkV2.Meta().(*config.MongoDBClient).Atlas

rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("not found: %s", resourceName)
}

if rs.Primary.ID == "" {
return fmt.Errorf("no ID is set")
}

ids := conversion.DecodeStateID(rs.Primary.ID)

_, _, err := conn.APIKeys.Get(context.Background(), ids["org_id"], ids["api_key_id"])
_, _, err := acc.Conn().APIKeys.Get(context.Background(), ids["org_id"], ids["api_key_id"])
if err != nil {
return fmt.Errorf("API Key (%s) does not exist", ids["api_key_id"])
}

return nil
}
}

func testAccCheckMongoDBAtlasAPIKeyDestroy(s *terraform.State) error {
conn := acc.TestAccProviderSdkV2.Meta().(*config.MongoDBClient).Atlas

for _, rs := range s.RootModule().Resources {
if rs.Type != "mongodbatlas_api_key" {
continue
}

ids := conversion.DecodeStateID(rs.Primary.ID)

_, _, err := conn.APIKeys.Get(context.Background(), ids["org_id"], ids["role_name"])
_, _, err := acc.Conn().APIKeys.Get(context.Background(), ids["org_id"], ids["role_name"])
if err == nil {
return fmt.Errorf("API Key (%s) still exists", ids["role_name"])
}
}

return nil
}

Expand Down
8 changes: 2 additions & 6 deletions internal/service/atlasuser/data_source_atlas_user_test.go
Expand Up @@ -9,7 +9,6 @@ import (

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
"go.mongodb.org/atlas-sdk/v20231115004/admin"
)
Expand Down Expand Up @@ -89,8 +88,7 @@ func TestAccConfigDSAtlasUser_InvalidAttrCombination(t *testing.T) {

func fetchUser(t *testing.T, userID string) *admin.CloudAppUser {
t.Helper()
connV2 := acc.TestMongoDBClient.(*config.MongoDBClient).AtlasV2
userResp, _, err := connV2.MongoDBCloudUsersApi.GetUser(context.Background(), userID).Execute()
userResp, _, err := acc.ConnV2().MongoDBCloudUsersApi.GetUser(context.Background(), userID).Execute()
if err != nil {
t.Fatalf("the Atlas User (%s) could not be fetched: %v", userID, err)
}
Expand All @@ -99,9 +97,7 @@ func fetchUser(t *testing.T, userID string) *admin.CloudAppUser {

func fetchUserByUsername(t *testing.T, username string) *admin.CloudAppUser {
t.Helper()
connV2 := acc.TestMongoDBClient.(*config.MongoDBClient).AtlasV2

userResp, _, err := connV2.MongoDBCloudUsersApi.GetUserByUsername(context.Background(), username).Execute()
userResp, _, err := acc.ConnV2().MongoDBCloudUsersApi.GetUserByUsername(context.Background(), username).Execute()
if err != nil {
t.Fatalf("the Atlas User (%s) could not be fetched: %v", username, err)
}
Expand Down
8 changes: 2 additions & 6 deletions internal/service/atlasuser/data_source_atlas_users_test.go
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/service/atlasuser"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
"go.mongodb.org/atlas-sdk/v20231115004/admin"
Expand Down Expand Up @@ -204,8 +203,7 @@ func TestAccConfigDSAtlasUsers_InvalidAttrCombinations(t *testing.T) {

func fetchOrgUsers(t *testing.T, orgID string) *admin.PaginatedAppUser {
t.Helper()
connV2 := acc.TestMongoDBClient.(*config.MongoDBClient).AtlasV2
users, _, err := connV2.OrganizationsApi.ListOrganizationUsers(context.Background(), orgID).Execute()
users, _, err := acc.ConnV2().OrganizationsApi.ListOrganizationUsers(context.Background(), orgID).Execute()
if err != nil {
t.Fatalf("the Atlas Users for Org(%s) could not be fetched: %v", orgID, err)
}
Expand Down Expand Up @@ -286,8 +284,6 @@ func testAccDSMongoDBAtlasUsersByTeamWithPagination(orgID, teamName, username st

func testAccCheckMongoDBAtlasOrgWithUsersExists(dataSourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
connV2 := acc.TestMongoDBClient.(*config.MongoDBClient).AtlasV2

rs, ok := s.RootModule().Resources[dataSourceName]
if !ok {
return fmt.Errorf("not found: %s", dataSourceName)
Expand All @@ -298,7 +294,7 @@ func testAccCheckMongoDBAtlasOrgWithUsersExists(dataSourceName string) resource.
return fmt.Errorf("org_id not defined in data source: %s", dataSourceName)
}

apiResp, _, err := connV2.OrganizationsApi.ListOrganizationUsers(context.Background(), orgID).Execute()
apiResp, _, err := acc.ConnV2().OrganizationsApi.ListOrganizationUsers(context.Background(), orgID).Execute()

if err != nil {
return fmt.Errorf("unable to determine if users exist in org: %s", orgID)
Expand Down

0 comments on commit c58ff01

Please sign in to comment.