diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 18d2774..c28954f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -28,6 +28,14 @@ jobs: go test -v ./... -coverprofile=coverage.out env: TF_ACC: '1' + MC_API_KEY_ID: ${{ secrets.ACC_TEST_MC_API_KEY_ID }} + MC_API_KEY_TOKEN: ${{ secrets.ACC_TEST_MC_API_KEY_TOKEN }} + BQ_SERVICE_ACCOUNT: ${{ secrets.ACC_TEST_BQ_SERVICE_ACCOUNT }} + PG_HOST: ${{ secrets.ACC_TEST_PG_HOST }} + PG_PORT: ${{ secrets.ACC_TEST_PG_PORT }} + PG_DATABASE: ${{ secrets.ACC_TEST_PG_DATABASE }} + PG_USER: ${{ secrets.ACC_TEST_PG_USER }} + PG_PASSWORD: ${{ secrets.ACC_TEST_PG_PASSWORD }} - uses: actions/upload-artifact@v3 with: name: coverage diff --git a/monte_carlo/client/monte_carlo_client.go b/client/monte_carlo_client.go similarity index 100% rename from monte_carlo/client/monte_carlo_client.go rename to client/monte_carlo_client.go diff --git a/go.mod b/go.mod index 267abb5..dced18b 100644 --- a/go.mod +++ b/go.mod @@ -5,11 +5,10 @@ go 1.21.1 require ( github.com/hashicorp/terraform-plugin-framework v1.4.2 github.com/hashicorp/terraform-plugin-framework-validators v0.12.0 - github.com/hashicorp/terraform-plugin-go v0.19.0 + github.com/hashicorp/terraform-plugin-go v0.19.1 github.com/hashicorp/terraform-plugin-log v0.9.0 github.com/hashicorp/terraform-plugin-testing v1.5.1 github.com/hasura/go-graphql-client v0.10.0 - github.com/stretchr/testify v1.8.4 ) require ( @@ -17,7 +16,6 @@ require ( github.com/agext/levenshtein v1.2.3 // indirect github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect github.com/cloudflare/circl v1.3.5 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect github.com/fatih/color v1.15.0 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/google/go-cmp v0.6.0 // indirect @@ -37,7 +35,7 @@ require ( github.com/hashicorp/terraform-exec v0.19.0 // indirect github.com/hashicorp/terraform-json v0.17.1 // indirect github.com/hashicorp/terraform-plugin-sdk/v2 v2.29.0 // indirect - github.com/hashicorp/terraform-registry-address v0.2.2 // indirect + github.com/hashicorp/terraform-registry-address v0.2.3 // indirect github.com/hashicorp/terraform-svchost v0.1.1 // indirect github.com/hashicorp/yamux v0.1.1 // indirect github.com/kr/pretty v0.3.1 // indirect @@ -49,10 +47,9 @@ require ( github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/oklog/run v1.1.0 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/stretchr/objx v0.5.1 // indirect + github.com/stretchr/testify v1.8.2 // indirect github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect - github.com/vmihailenco/msgpack/v5 v5.4.0 // indirect + github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/zclconf/go-cty v1.14.1 // indirect golang.org/x/crypto v0.14.0 // indirect @@ -66,6 +63,5 @@ require ( google.golang.org/grpc v1.59.0 // indirect google.golang.org/protobuf v1.31.0 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect nhooyr.io/websocket v1.8.9 // indirect ) diff --git a/go.sum b/go.sum index 80ebe20..4865b64 100644 --- a/go.sum +++ b/go.sum @@ -90,16 +90,16 @@ github.com/hashicorp/terraform-plugin-framework v1.4.2 h1:P7a7VP1GZbjc4rv921Xy5O github.com/hashicorp/terraform-plugin-framework v1.4.2/go.mod h1:GWl3InPFZi2wVQmdVnINPKys09s9mLmTZr95/ngLnbY= github.com/hashicorp/terraform-plugin-framework-validators v0.12.0 h1:HOjBuMbOEzl7snOdOoUfE2Jgeto6JOjLVQ39Ls2nksc= github.com/hashicorp/terraform-plugin-framework-validators v0.12.0/go.mod h1:jfHGE/gzjxYz6XoUwi/aYiiKrJDeutQNUtGQXkaHklg= -github.com/hashicorp/terraform-plugin-go v0.19.0 h1:BuZx/6Cp+lkmiG0cOBk6Zps0Cb2tmqQpDM3iAtnhDQU= -github.com/hashicorp/terraform-plugin-go v0.19.0/go.mod h1:EhRSkEPNoylLQntYsk5KrDHTZJh9HQoumZXbOGOXmec= +github.com/hashicorp/terraform-plugin-go v0.19.1 h1:lf/jTGTeELcz5IIbn/94mJdmnTjRYm6S6ct/JqCSr50= +github.com/hashicorp/terraform-plugin-go v0.19.1/go.mod h1:5NMIS+DXkfacX6o5HCpswda5yjkSYfKzn1Nfl9l+qRs= github.com/hashicorp/terraform-plugin-log v0.9.0 h1:i7hOA+vdAItN1/7UrfBqBwvYPQ9TFvymaRGZED3FCV0= github.com/hashicorp/terraform-plugin-log v0.9.0/go.mod h1:rKL8egZQ/eXSyDqzLUuwUYLVdlYeamldAHSxjUFADow= github.com/hashicorp/terraform-plugin-sdk/v2 v2.29.0 h1:wcOKYwPI9IorAJEBLzgclh3xVolO7ZorYd6U1vnok14= github.com/hashicorp/terraform-plugin-sdk/v2 v2.29.0/go.mod h1:qH/34G25Ugdj5FcM95cSoXzUgIbgfhVLXCcEcYaMwq8= github.com/hashicorp/terraform-plugin-testing v1.5.1 h1:T4aQh9JAhmWo4+t1A7x+rnxAJHCDIYW9kXyo4sVO92c= github.com/hashicorp/terraform-plugin-testing v1.5.1/go.mod h1:dg8clO6K59rZ8w9EshBmDp1CxTIPu3yA4iaDpX1h5u0= -github.com/hashicorp/terraform-registry-address v0.2.2 h1:lPQBg403El8PPicg/qONZJDC6YlgCVbWDtNmmZKtBno= -github.com/hashicorp/terraform-registry-address v0.2.2/go.mod h1:LtwNbCihUoUZ3RYriyS2wF/lGPB6gF9ICLRtuDk7hSo= +github.com/hashicorp/terraform-registry-address v0.2.3 h1:2TAiKJ1A3MAkZlH1YI/aTVcLZRu7JseiXNRHbOAyoTI= +github.com/hashicorp/terraform-registry-address v0.2.3/go.mod h1:lFHA76T8jfQteVfT7caREqguFrW3c4MFSPhZB7HHgUM= github.com/hashicorp/terraform-svchost v0.1.1 h1:EZZimZ1GxdqFRinZ1tpJwVxxt49xc/S52uzrw4x0jKQ= github.com/hashicorp/terraform-svchost v0.1.1/go.mod h1:mNsjQfZyf/Jhz35v6/0LWcv26+X7JPS+buii2c9/ctc= github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE= @@ -157,19 +157,16 @@ github.com/skeema/knownhosts v1.2.0/go.mod h1:g4fPeYpque7P0xefxtGzV81ihjC8sX2Iqp github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/objx v0.5.1 h1:4VhoImhV/Bm0ToFkXFi8hXNXwpDRZ/ynw3amt82mzq0= -github.com/stretchr/objx v0.5.1/go.mod h1:/iHQpkQwBD6DLUmQ4pE+s1TXdob1mORJ4/UFdrifcy0= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI= github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= -github.com/vmihailenco/msgpack/v5 v5.4.0 h1:hRM0digJwyR6vll33NNAwCFguy5JuBD6jxDmQP3l608= -github.com/vmihailenco/msgpack/v5 v5.4.0/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= +github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= +github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= diff --git a/internal/acctest/acctest.go b/internal/acctest/acctest.go new file mode 100644 index 0000000..18065de --- /dev/null +++ b/internal/acctest/acctest.go @@ -0,0 +1,27 @@ +package acctest + +import ( + "os" + "testing" + + "github.com/kiwicom/terraform-provider-montecarlo/internal" + + "github.com/hashicorp/terraform-plugin-framework/providerserver" + "github.com/hashicorp/terraform-plugin-go/tfprotov6" +) + +// testAccProtoV6ProviderFactories are used to instantiate a provider during +// acceptance testing. The factory function will be invoked for every Terraform +// CLI command executed to create a provider server to which the CLI can +// reattach. +var TestAccProviderFactories = map[string]func() (tfprotov6.ProviderServer, error){ + "montecarlo": providerserver.NewProtocol6WithError(internal.New("test")()), +} + +func TestAccPreCheck(t *testing.T) { + if v := os.Getenv("MC_API_KEY_ID"); v == "" { + t.Fatalf("'MC_API_KEY_ID' must be set for acceptance tests") + } else if v := os.Getenv("MC_API_KEY_TOKEN"); v == "" { + t.Fatalf("'MC_API_KEY_TOKEN' must be set for acceptance tests") + } +} diff --git a/monte_carlo/resources/iam_group.go b/internal/authorization/iam_group.go similarity index 94% rename from monte_carlo/resources/iam_group.go rename to internal/authorization/iam_group.go index 25dd077..a14175d 100644 --- a/monte_carlo/resources/iam_group.go +++ b/internal/authorization/iam_group.go @@ -1,11 +1,11 @@ -package resources +package authorization import ( "context" "fmt" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" + "github.com/kiwicom/terraform-provider-montecarlo/client" + "github.com/kiwicom/terraform-provider-montecarlo/internal/common" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework/attr" @@ -120,7 +120,7 @@ func (r *IamGroupResource) Create(ctx context.Context, req resource.CreateReques "label": data.Name.ValueString(), "description": data.Description.ValueString(), "roles": []string{data.Role.ValueString()}, - "domainRestrictionIds": normalize[client.UUID](data.Domains), + "domainRestrictionIds": common.TfStringsTo[client.UUID](data.Domains), "ssoGroup": data.SsoGroup.ValueStringPointer(), } @@ -164,8 +164,8 @@ func (r *IamGroupResource) Read(ctx context.Context, req resource.ReadRequest, r } else { data.Label = types.StringValue(found.Label) data.Description = types.StringValue(found.Description) - data.Role = denormalize(rolesToNames(found.Roles))[0] - data.Domains = denormalize(domainsToUuids[string](found.DomainRestrictions)) + data.Role = common.TfStringsFrom(rolesToNames(found.Roles))[0] + data.Domains = common.TfStringsFrom(domainsToUuids[string](found.DomainRestrictions)) data.SsoGroup = types.StringPointerValue(found.SsoGroup) resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) } @@ -184,7 +184,7 @@ func (r *IamGroupResource) Update(ctx context.Context, req resource.UpdateReques "label": data.Name.ValueString(), "description": data.Description.ValueString(), "roles": []string{data.Role.ValueString()}, - "domainRestrictionIds": normalize[client.UUID](data.Domains), + "domainRestrictionIds": common.TfStringsTo[client.UUID](data.Domains), "ssoGroup": data.SsoGroup.ValueStringPointer(), } diff --git a/internal/authorization/iam_group_test.go b/internal/authorization/iam_group_test.go new file mode 100644 index 0000000..dad1dd9 --- /dev/null +++ b/internal/authorization/iam_group_test.go @@ -0,0 +1,71 @@ +package authorization_test + +import ( + "os" + "testing" + + "github.com/kiwicom/terraform-provider-montecarlo/internal/acctest" + + "github.com/hashicorp/terraform-plugin-testing/config" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" +) + +func TestAccIamGroupResource(t *testing.T) { + mc_api_key_id := os.Getenv("MC_API_KEY_ID") + mc_api_key_token := os.Getenv("MC_API_KEY_TOKEN") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.TestAccPreCheck(t) }, + Steps: []resource.TestStep{ + { // Create and Read testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigFile: config.TestNameFile("create.tf"), + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("montecarlo_iam_group.test", "name", "group-1"), + resource.TestCheckResourceAttr("montecarlo_iam_group.test", "label", "group-1"), + resource.TestCheckResourceAttr("montecarlo_iam_group.test", "description", ""), + resource.TestCheckResourceAttr("montecarlo_iam_group.test", "role", "mcd/editor"), + resource.TestCheckResourceAttr("montecarlo_iam_group.test", "domains.#", "0"), + resource.TestCheckNoResourceAttr("montecarlo_iam_group.test", "ssoGroup"), + ), + }, + { // ImportState testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + }, + ResourceName: "montecarlo_iam_group.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: func(s *terraform.State) (string, error) { + return s.RootModule().Resources["montecarlo_iam_group.test"].Primary.Attributes["name"], nil + }, + ImportStateVerifyIdentifierAttribute: "name", + }, + { // Update and Read testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigFile: config.TestNameFile("update.tf"), + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("montecarlo_iam_group.test", "name", "group-1"), + resource.TestCheckResourceAttr("montecarlo_iam_group.test", "label", "group-1"), + resource.TestCheckResourceAttr("montecarlo_iam_group.test", "description", ""), + resource.TestCheckResourceAttr("montecarlo_iam_group.test", "role", "mcd/viewer"), + resource.TestCheckResourceAttr("montecarlo_iam_group.test", "domains.#", "2"), + resource.TestCheckTypeSetElemAttr("montecarlo_iam_group.test", "domains.*", "ba0c4080-089d-4377-8878-466c31d19807"), + resource.TestCheckTypeSetElemAttr("montecarlo_iam_group.test", "domains.*", "dd4cda19-1c5c-4339-9628-76376c9e281e"), + resource.TestCheckResourceAttr("montecarlo_iam_group.test", "sso_group", "ssoGroup1"), + ), + }, + }, + }) +} diff --git a/monte_carlo/resources/iam_member.go b/internal/authorization/iam_member.go similarity index 96% rename from monte_carlo/resources/iam_member.go rename to internal/authorization/iam_member.go index 5b35b61..8477097 100644 --- a/monte_carlo/resources/iam_member.go +++ b/internal/authorization/iam_member.go @@ -1,4 +1,4 @@ -package resources +package authorization import ( "context" @@ -7,8 +7,8 @@ import ( "slices" "strings" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" + "github.com/kiwicom/terraform-provider-montecarlo/client" + "github.com/kiwicom/terraform-provider-montecarlo/internal/common" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework/path" @@ -122,7 +122,7 @@ func (r *IamMemberResource) Create(ctx context.Context, req resource.CreateReque var group *client.AuthorizationGroup groupName := strings.Split(data.Group.ValueString(), "groups/")[1] if index := slices.IndexFunc(getGroupResult.GetAuthorizationGroups, func(group client.AuthorizationGroup) bool { - return group.SsoGroup == nil && group.Name == groupName + return (group.SsoGroup == nil || *group.SsoGroup == "") && group.Name == groupName }); index >= 0 { group = &getGroupResult.GetAuthorizationGroups[index] } else { @@ -187,7 +187,7 @@ func (r *IamMemberResource) Read(ctx context.Context, req resource.ReadRequest, var group *client.AuthorizationGroup groupName := strings.Split(data.Group.ValueString(), "groups/")[1] if index := slices.IndexFunc(getGroupResult.GetAuthorizationGroups, func(group client.AuthorizationGroup) bool { - return group.SsoGroup == nil && group.Name == groupName + return (group.SsoGroup == nil || *group.SsoGroup == "") && group.Name == groupName }); index >= 0 { group = &getGroupResult.GetAuthorizationGroups[index] } else { diff --git a/internal/authorization/iam_member_test.go b/internal/authorization/iam_member_test.go new file mode 100644 index 0000000..35e0d6e --- /dev/null +++ b/internal/authorization/iam_member_test.go @@ -0,0 +1,60 @@ +package authorization_test + +import ( + "os" + "testing" + + "github.com/kiwicom/terraform-provider-montecarlo/internal/acctest" + + "github.com/hashicorp/terraform-plugin-testing/config" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +func TestAccIamMemberResource(t *testing.T) { + mc_api_key_id := os.Getenv("MC_API_KEY_ID") + mc_api_key_token := os.Getenv("MC_API_KEY_TOKEN") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.TestAccPreCheck(t) }, + Steps: []resource.TestStep{ + { // Create and Read testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigFile: config.TestNameFile("create.tf"), + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("montecarlo_iam_member.test", "group", "groups/TestAccIamMemberResource"), + resource.TestCheckResourceAttr("montecarlo_iam_member.test", "member", "user:ndopjera@gmail.com"), + resource.TestCheckResourceAttr("montecarlo_iam_member.test", "member_id", "21ddb883-7586-4034-9767-e5f966ec10df"), + ), + }, + { // ImportState testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + }, + ResourceName: "montecarlo_iam_member.test", + ImportState: true, + ImportStateVerify: true, + ImportStateId: "groups/TestAccIamMemberResource,user:ndopjera@gmail.com", + ImportStateVerifyIdentifierAttribute: "group", + }, + { // Update and Read testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigFile: config.TestNameFile("update_group.tf"), + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("montecarlo_iam_member.test", "group", "groups/TestAccIamMemberResource2"), + resource.TestCheckResourceAttr("montecarlo_iam_member.test", "member", "user:ndopjera@gmail.com"), + resource.TestCheckResourceAttr("montecarlo_iam_member.test", "member_id", "21ddb883-7586-4034-9767-e5f966ec10df"), + ), + }, + }, + }) +} diff --git a/internal/authorization/testdata/TestAccIamGroupResource/create.tf b/internal/authorization/testdata/TestAccIamGroupResource/create.tf new file mode 100644 index 0000000..f1665b5 --- /dev/null +++ b/internal/authorization/testdata/TestAccIamGroupResource/create.tf @@ -0,0 +1,19 @@ +variable "montecarlo_api_key_id" { + type = string +} + +variable "montecarlo_api_key_token" { + type = string +} + +provider "montecarlo" { + account_service_key = { + id = var.montecarlo_api_key_id # (secret) + token = var.montecarlo_api_key_token # (secret) + } +} + +resource "montecarlo_iam_group" "test" { + name = "group-1" + role = "mcd/editor" +} diff --git a/internal/authorization/testdata/TestAccIamGroupResource/update.tf b/internal/authorization/testdata/TestAccIamGroupResource/update.tf new file mode 100644 index 0000000..7933b68 --- /dev/null +++ b/internal/authorization/testdata/TestAccIamGroupResource/update.tf @@ -0,0 +1,24 @@ +variable "montecarlo_api_key_id" { + type = string +} + +variable "montecarlo_api_key_token" { + type = string +} + +provider "montecarlo" { + account_service_key = { + id = var.montecarlo_api_key_id # (secret) + token = var.montecarlo_api_key_token # (secret) + } +} + +resource "montecarlo_iam_group" "test" { + name = "group-1" + role = "mcd/viewer" + sso_group = "ssoGroup1" + domains = [ + "ba0c4080-089d-4377-8878-466c31d19807", + "dd4cda19-1c5c-4339-9628-76376c9e281e" + ] +} diff --git a/internal/authorization/testdata/TestAccIamMemberResource/create.tf b/internal/authorization/testdata/TestAccIamMemberResource/create.tf new file mode 100644 index 0000000..a61e6d1 --- /dev/null +++ b/internal/authorization/testdata/TestAccIamMemberResource/create.tf @@ -0,0 +1,19 @@ +variable "montecarlo_api_key_id" { + type = string +} + +variable "montecarlo_api_key_token" { + type = string +} + +provider "montecarlo" { + account_service_key = { + id = var.montecarlo_api_key_id # (secret) + token = var.montecarlo_api_key_token # (secret) + } +} + +resource "montecarlo_iam_member" "test" { + group = "groups/TestAccIamMemberResource" + member = "user:ndopjera@gmail.com" +} diff --git a/internal/authorization/testdata/TestAccIamMemberResource/update_group.tf b/internal/authorization/testdata/TestAccIamMemberResource/update_group.tf new file mode 100644 index 0000000..bbeb3fb --- /dev/null +++ b/internal/authorization/testdata/TestAccIamMemberResource/update_group.tf @@ -0,0 +1,19 @@ +variable "montecarlo_api_key_id" { + type = string +} + +variable "montecarlo_api_key_token" { + type = string +} + +provider "montecarlo" { + account_service_key = { + id = var.montecarlo_api_key_id # (secret) + token = var.montecarlo_api_key_token # (secret) + } +} + +resource "montecarlo_iam_member" "test" { + group = "groups/TestAccIamMemberResource2" + member = "user:ndopjera@gmail.com" +} diff --git a/monte_carlo/common/common.go b/internal/common/common.go similarity index 82% rename from monte_carlo/common/common.go rename to internal/common/common.go index ee6aef3..5e2ff32 100644 --- a/monte_carlo/common/common.go +++ b/internal/common/common.go @@ -3,12 +3,13 @@ package common import ( "fmt" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" + "github.com/kiwicom/terraform-provider-montecarlo/client" "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-framework/types/basetypes" ) // Cyclic types commonly shared in this provider packages @@ -76,3 +77,19 @@ func Configure[Req resource.ConfigureRequest | datasource.ConfigureRequest](req return nil, diags } } + +func TfStringsTo[T ~string](in []basetypes.StringValue) []T { + res := make([]T, len(in)) + for i, element := range in { + res[i] = T(element.ValueString()) + } + return res +} + +func TfStringsFrom(in []string) []types.String { + res := make([]types.String, len(in)) + for i, element := range in { + res[i] = types.StringValue(element) + } + return res +} diff --git a/monte_carlo/resources/domain.go b/internal/domain.go similarity index 91% rename from monte_carlo/resources/domain.go rename to internal/domain.go index 65571d7..993aad0 100644 --- a/monte_carlo/resources/domain.go +++ b/internal/domain.go @@ -1,12 +1,12 @@ -package resources +package internal import ( "context" "encoding/json" "fmt" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" + "github.com/kiwicom/terraform-provider-montecarlo/client" + "github.com/kiwicom/terraform-provider-montecarlo/internal/common" "github.com/hashicorp/terraform-plugin-framework-validators/resourcevalidator" "github.com/hashicorp/terraform-plugin-framework/attr" @@ -18,7 +18,6 @@ import ( "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-framework/types/basetypes" ) // Ensure provider defined types fully satisfy framework interfaces. @@ -128,7 +127,7 @@ func (r *DomainResource) Create(ctx context.Context, req resource.CreateRequest, createResult := client.CreateOrUpdateDomain{} variables := map[string]interface{}{ "uuid": (*client.UUID)(nil), - "assignments": normalize[string](data.Assignments), + "assignments": common.TfStringsTo[string](data.Assignments), "tags": common.ToTagPairs(data.Tags), "name": data.Name.ValueString(), "description": data.Description.ValueString(), @@ -174,7 +173,7 @@ func (r *DomainResource) Read(ctx context.Context, req resource.ReadRequest, res } data.Tags = common.FromTagPairs(getResult.GetDomain.Tags) - data.Assignments = denormalize(getResult.GetDomain.Assignments) + data.Assignments = common.TfStringsFrom(getResult.GetDomain.Assignments) data.Name = types.StringValue(getResult.GetDomain.Name) data.Description = types.StringValue(getResult.GetDomain.Description) resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) @@ -190,7 +189,7 @@ func (r *DomainResource) Update(ctx context.Context, req resource.UpdateRequest, createResult := client.CreateOrUpdateDomain{} variables := map[string]interface{}{ "uuid": client.UUID(data.Uuid.ValueString()), - "assignments": normalize[string](data.Assignments), + "assignments": common.TfStringsTo[string](data.Assignments), "tags": common.ToTagPairs(data.Tags), "name": data.Name.ValueString(), "description": data.Description.ValueString(), @@ -229,19 +228,3 @@ func (r *DomainResource) Delete(ctx context.Context, req resource.DeleteRequest, func (r *DomainResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { resource.ImportStatePassthroughID(ctx, path.Root("uuid"), req, resp) } - -func normalize[T ~string](in []basetypes.StringValue) []T { - res := make([]T, len(in)) - for i, element := range in { - res[i] = T(element.ValueString()) - } - return res -} - -func denormalize(in []string) []types.String { - res := make([]types.String, len(in)) - for i, element := range in { - res[i] = types.StringValue(element) - } - return res -} diff --git a/internal/domain_test.go b/internal/domain_test.go new file mode 100644 index 0000000..f9428df --- /dev/null +++ b/internal/domain_test.go @@ -0,0 +1,92 @@ +package internal_test + +import ( + "os" + "testing" + + "github.com/kiwicom/terraform-provider-montecarlo/internal/acctest" + + "github.com/hashicorp/terraform-plugin-testing/config" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" +) + +func TestAccDomainResource(t *testing.T) { + mc_api_key_id := os.Getenv("MC_API_KEY_ID") + mc_api_key_token := os.Getenv("MC_API_KEY_TOKEN") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.TestAccPreCheck(t) }, + Steps: []resource.TestStep{ + { // Create and Read testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigFile: config.TestNameFile("create.tf"), + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + }, + Check: resource.ComposeAggregateTestCheckFunc( + //resource.TestCheckResourceAttr("montecarlo_domain.test", "uuid", ), + resource.TestCheckResourceAttr("montecarlo_domain.test", "name", "domain1"), + resource.TestCheckResourceAttr("montecarlo_domain.test", "description", "Domain test description"), + resource.TestCheckResourceAttr("montecarlo_domain.test", "assignments.#", "0"), + resource.TestCheckResourceAttr("montecarlo_domain.test", "tags.#", "2"), + resource.TestCheckTypeSetElemNestedAttrs("montecarlo_domain.test", "tags.*", map[string]string{ + "name": "dataset_tables_1", + }), + resource.TestCheckTypeSetElemNestedAttrs("montecarlo_domain.test", "tags.*", map[string]string{ + "name": "owner", + "value": "bi-internal", + }), + ), + }, + { // ImportState testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + }, + ResourceName: "montecarlo_domain.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: func(s *terraform.State) (string, error) { + return s.RootModule().Resources["montecarlo_domain.test"].Primary.Attributes["uuid"], nil + }, + ImportStateVerifyIdentifierAttribute: "uuid", + }, + { // Update and Read testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigFile: config.TestNameFile("update.tf"), + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + }, + Check: resource.ComposeAggregateTestCheckFunc( + //resource.TestCheckResourceAttr("montecarlo_domain.test", "uuid", domainUuid), + resource.TestCheckResourceAttr("montecarlo_domain.test", "name", "domain2"), + resource.TestCheckResourceAttr("montecarlo_domain.test", "description", "Domain test description"), + resource.TestCheckResourceAttr("montecarlo_domain.test", "assignments.#", "0"), + resource.TestCheckResourceAttr("montecarlo_domain.test", "tags.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs("montecarlo_domain.test", "tags.*", map[string]string{ + "name": "dataset_tables_2", + }), + ), + }, + { + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigFile: config.TestNameFile("update_assignments.tf"), + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + }, + Check: resource.ComposeAggregateTestCheckFunc( + //resource.TestCheckResourceAttr("montecarlo_domain.test", "uuid", domainUuid), + resource.TestCheckResourceAttr("montecarlo_domain.test", "name", "domain2"), + resource.TestCheckResourceAttr("montecarlo_domain.test", "description", "Domain test description 2"), + resource.TestCheckResourceAttr("montecarlo_domain.test", "assignments.#", "0"), + resource.TestCheckResourceAttr("montecarlo_domain.test", "tags.#", "0"), + ), + }, + }, + }) +} diff --git a/monte_carlo/provider/provider.go b/internal/provider.go similarity index 81% rename from monte_carlo/provider/provider.go rename to internal/provider.go index e2391f4..77b22c2 100644 --- a/monte_carlo/provider/provider.go +++ b/internal/provider.go @@ -1,13 +1,13 @@ -package provider +package internal import ( "context" "fmt" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" - datasources "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/data_sources" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/resources" + "github.com/kiwicom/terraform-provider-montecarlo/client" + "github.com/kiwicom/terraform-provider-montecarlo/internal/authorization" + "github.com/kiwicom/terraform-provider-montecarlo/internal/common" + "github.com/kiwicom/terraform-provider-montecarlo/internal/warehouse" "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/provider" @@ -93,22 +93,22 @@ func (p *Provider) Configure(ctx context.Context, req provider.ConfigureRequest, func (p *Provider) Resources(ctx context.Context) []func() resource.Resource { return []func() resource.Resource{ - resources.NewBigQueryWarehouseResource, - resources.NewTransactionalWarehouseResource, - resources.NewDomainResource, - resources.NewIamGroupResource, - resources.NewIamMemberResource, + warehouse.NewBigQueryWarehouseResource, + warehouse.NewTransactionalWarehouseResource, + NewDomainResource, + authorization.NewIamGroupResource, + authorization.NewIamMemberResource, } } func (p *Provider) DataSources(ctx context.Context) []func() datasource.DataSource { return []func() datasource.DataSource{ - datasources.NewWarehouseDatasource, + warehouse.NewWarehouseDatasource, } } -func New(version string, context *common.ProviderContext) func() provider.Provider { +func New(version string) func() provider.Provider { return func() provider.Provider { - return &Provider{version: version, context: context} + return &Provider{version: version} } } diff --git a/internal/testdata/TestAccDomainResource/create.tf b/internal/testdata/TestAccDomainResource/create.tf new file mode 100644 index 0000000..79edf8a --- /dev/null +++ b/internal/testdata/TestAccDomainResource/create.tf @@ -0,0 +1,28 @@ +variable "montecarlo_api_key_id" { + type = string +} + +variable "montecarlo_api_key_token" { + type = string +} + +provider "montecarlo" { + account_service_key = { + id = var.montecarlo_api_key_id # (secret) + token = var.montecarlo_api_key_token # (secret) + } +} + +resource "montecarlo_domain" "test" { + name = "domain1" + description = "Domain test description" + tags = [ + { + name = "owner" + value = "bi-internal" + }, + { + name = "dataset_tables_1" + } + ] +} diff --git a/internal/testdata/TestAccDomainResource/update.tf b/internal/testdata/TestAccDomainResource/update.tf new file mode 100644 index 0000000..e590799 --- /dev/null +++ b/internal/testdata/TestAccDomainResource/update.tf @@ -0,0 +1,24 @@ +variable "montecarlo_api_key_id" { + type = string +} + +variable "montecarlo_api_key_token" { + type = string +} + +provider "montecarlo" { + account_service_key = { + id = var.montecarlo_api_key_id # (secret) + token = var.montecarlo_api_key_token # (secret) + } +} + +resource "montecarlo_domain" "test" { + name = "domain2" + description = "Domain test description" + tags = [ + { + name = "dataset_tables_2" + } + ] +} diff --git a/internal/testdata/TestAccDomainResource/update_assignments.tf b/internal/testdata/TestAccDomainResource/update_assignments.tf new file mode 100644 index 0000000..f989ece --- /dev/null +++ b/internal/testdata/TestAccDomainResource/update_assignments.tf @@ -0,0 +1,23 @@ +variable "montecarlo_api_key_id" { + type = string +} + +variable "montecarlo_api_key_token" { + type = string +} + +provider "montecarlo" { + account_service_key = { + id = var.montecarlo_api_key_id # (secret) + token = var.montecarlo_api_key_token # (secret) + } +} + +resource "montecarlo_domain" "test" { + name = "domain2" + description = "Domain test description 2" + assignments = [ + #"MCON++a84380ed-b962-4bd3-b150-04bc38a209d5++427a1600-2653-40c5-a1e7-5ec98703ee9d++project++gcp-project1-722af1c6", + #"MCON++a84380ed-b962-4bd3-b150-04bc38a209d5++e7c59fd6-7ca8-41e7-8325-062ea38d3df5++dataset++postgre-dataset-1" + ] +} diff --git a/monte_carlo/resources/bigquery_warehouse.go b/internal/warehouse/bigquery_warehouse.go similarity index 99% rename from monte_carlo/resources/bigquery_warehouse.go rename to internal/warehouse/bigquery_warehouse.go index d264e84..95c17cb 100644 --- a/monte_carlo/resources/bigquery_warehouse.go +++ b/internal/warehouse/bigquery_warehouse.go @@ -1,4 +1,4 @@ -package resources +package warehouse import ( "context" @@ -7,8 +7,8 @@ import ( "fmt" "strings" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" + "github.com/kiwicom/terraform-provider-montecarlo/client" + "github.com/kiwicom/terraform-provider-montecarlo/internal/common" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework/diag" diff --git a/internal/warehouse/bigquery_warehouse_test.go b/internal/warehouse/bigquery_warehouse_test.go new file mode 100644 index 0000000..835076f --- /dev/null +++ b/internal/warehouse/bigquery_warehouse_test.go @@ -0,0 +1,79 @@ +package warehouse_test + +import ( + "fmt" + "os" + "testing" + + "github.com/kiwicom/terraform-provider-montecarlo/internal/acctest" + + "github.com/hashicorp/terraform-plugin-testing/config" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" +) + +func TestAccBigQueryWarehouseResource(t *testing.T) { + mc_api_key_id := os.Getenv("MC_API_KEY_ID") + mc_api_key_token := os.Getenv("MC_API_KEY_TOKEN") + + collectorUuid := "a08d23fc-00a0-4c36-b568-82e9d0e67ad8" + serviceAccount := os.Getenv("BQ_SERVICE_ACCOUNT") + + if serviceAccount == "" { + t.Fatalf("'BQ_SERVICE_ACCOUNT' must be set for this acceptance tests") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.TestAccPreCheck(t) }, + Steps: []resource.TestStep{ + { // Create and Read testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigFile: config.TestNameFile("create.tf"), + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + "bq_service_account": config.StringVariable(serviceAccount), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "name", "test-warehouse"), + resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "collector_uuid", collectorUuid), + resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "service_account_key", serviceAccount), + resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "deletion_protection", "false"), + ), + }, + { // ImportState testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + "bq_service_account": config.StringVariable(serviceAccount), + }, + ResourceName: "montecarlo_bigquery_warehouse.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: func(s *terraform.State) (string, error) { + uuid := s.RootModule().Resources["montecarlo_bigquery_warehouse.test"].Primary.Attributes["uuid"] + connectionUuid := s.RootModule().Resources["montecarlo_bigquery_warehouse.test"].Primary.Attributes["connection_uuid"] + return fmt.Sprintf("%[1]s,%[2]s,%[3]s", uuid, connectionUuid, collectorUuid), nil + }, + ImportStateVerifyIdentifierAttribute: "uuid", + ImportStateVerifyIgnore: []string{"deletion_protection", "service_account_key"}, + }, + { // Update and Read testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigFile: config.TestNameFile("update.tf"), + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + "bq_service_account": config.StringVariable(serviceAccount), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "name", "test-warehouse-updated"), + resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "collector_uuid", collectorUuid), + resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "service_account_key", serviceAccount), + resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "deletion_protection", "false"), + ), + }, + }, + }) +} diff --git a/internal/warehouse/testdata/TestAccBigQueryWarehouseResource/create.tf b/internal/warehouse/testdata/TestAccBigQueryWarehouseResource/create.tf new file mode 100644 index 0000000..2569f14 --- /dev/null +++ b/internal/warehouse/testdata/TestAccBigQueryWarehouseResource/create.tf @@ -0,0 +1,25 @@ +variable "montecarlo_api_key_id" { + type = string +} + +variable "montecarlo_api_key_token" { + type = string +} + +provider "montecarlo" { + account_service_key = { + id = var.montecarlo_api_key_id # (secret) + token = var.montecarlo_api_key_token # (secret) + } +} + +variable "bq_service_account" { + type = string +} + +resource "montecarlo_bigquery_warehouse" "test" { + name = "test-warehouse" + collector_uuid = "a08d23fc-00a0-4c36-b568-82e9d0e67ad8" + service_account_key = var.bq_service_account + deletion_protection = false +} diff --git a/internal/warehouse/testdata/TestAccBigQueryWarehouseResource/update.tf b/internal/warehouse/testdata/TestAccBigQueryWarehouseResource/update.tf new file mode 100644 index 0000000..2938164 --- /dev/null +++ b/internal/warehouse/testdata/TestAccBigQueryWarehouseResource/update.tf @@ -0,0 +1,25 @@ +variable "montecarlo_api_key_id" { + type = string +} + +variable "montecarlo_api_key_token" { + type = string +} + +provider "montecarlo" { + account_service_key = { + id = var.montecarlo_api_key_id # (secret) + token = var.montecarlo_api_key_token # (secret) + } +} + +variable "bq_service_account" { + type = string +} + +resource "montecarlo_bigquery_warehouse" "test" { + name = "test-warehouse-updated" + collector_uuid = "a08d23fc-00a0-4c36-b568-82e9d0e67ad8" + service_account_key = var.bq_service_account + deletion_protection = false +} diff --git a/internal/warehouse/testdata/TestAccTransactionalWarehouseResource/create.tf b/internal/warehouse/testdata/TestAccTransactionalWarehouseResource/create.tf new file mode 100644 index 0000000..a036682 --- /dev/null +++ b/internal/warehouse/testdata/TestAccTransactionalWarehouseResource/create.tf @@ -0,0 +1,49 @@ +variable "montecarlo_api_key_id" { + type = string +} + +variable "montecarlo_api_key_token" { + type = string +} + +provider "montecarlo" { + account_service_key = { + id = var.montecarlo_api_key_id # (secret) + token = var.montecarlo_api_key_token # (secret) + } +} + +variable "pg_host" { + type = string +} + +variable "pg_port" { + type = number +} + +variable "pg_database" { + type = string +} + +variable "pg_user" { + type = string +} + +variable "pg_password" { + type = string +} + +resource "montecarlo_transactional_warehouse" "test" { + name = "name1" + collector_uuid = "a08d23fc-00a0-4c36-b568-82e9d0e67ad8" + db_type = "POSTGRES" # POSTGRES | MYSQL | SQL-SERVER + deletion_protection = false + + configuration = { + host = var.pg_host + port = var.pg_port + database = var.pg_database + username = var.pg_user #(secret) + password = var.pg_password #(secret) + } +} diff --git a/internal/warehouse/testdata/TestAccTransactionalWarehouseResource/update.tf b/internal/warehouse/testdata/TestAccTransactionalWarehouseResource/update.tf new file mode 100644 index 0000000..a036682 --- /dev/null +++ b/internal/warehouse/testdata/TestAccTransactionalWarehouseResource/update.tf @@ -0,0 +1,49 @@ +variable "montecarlo_api_key_id" { + type = string +} + +variable "montecarlo_api_key_token" { + type = string +} + +provider "montecarlo" { + account_service_key = { + id = var.montecarlo_api_key_id # (secret) + token = var.montecarlo_api_key_token # (secret) + } +} + +variable "pg_host" { + type = string +} + +variable "pg_port" { + type = number +} + +variable "pg_database" { + type = string +} + +variable "pg_user" { + type = string +} + +variable "pg_password" { + type = string +} + +resource "montecarlo_transactional_warehouse" "test" { + name = "name1" + collector_uuid = "a08d23fc-00a0-4c36-b568-82e9d0e67ad8" + db_type = "POSTGRES" # POSTGRES | MYSQL | SQL-SERVER + deletion_protection = false + + configuration = { + host = var.pg_host + port = var.pg_port + database = var.pg_database + username = var.pg_user #(secret) + password = var.pg_password #(secret) + } +} diff --git a/internal/warehouse/testdata/TestAccWarehouseDataSource/read.tf b/internal/warehouse/testdata/TestAccWarehouseDataSource/read.tf new file mode 100644 index 0000000..62536ab --- /dev/null +++ b/internal/warehouse/testdata/TestAccWarehouseDataSource/read.tf @@ -0,0 +1,18 @@ +variable "montecarlo_api_key_id" { + type = string +} + +variable "montecarlo_api_key_token" { + type = string +} + +provider "montecarlo" { + account_service_key = { + id = var.montecarlo_api_key_id # (secret) + token = var.montecarlo_api_key_token # (secret) + } +} + +data "montecarlo_warehouse" "test" { + uuid = "da6c0716-2724-4bfc-b5cc-7e0364faf979" +} diff --git a/monte_carlo/resources/transactional_warehouse.go b/internal/warehouse/transactional_warehouse.go similarity index 98% rename from monte_carlo/resources/transactional_warehouse.go rename to internal/warehouse/transactional_warehouse.go index 7167b9f..5c33940 100644 --- a/monte_carlo/resources/transactional_warehouse.go +++ b/internal/warehouse/transactional_warehouse.go @@ -1,4 +1,4 @@ -package resources +package warehouse import ( "context" @@ -6,8 +6,8 @@ import ( "fmt" "strings" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" + "github.com/kiwicom/terraform-provider-montecarlo/client" + "github.com/kiwicom/terraform-provider-montecarlo/internal/common" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework/diag" @@ -256,7 +256,7 @@ func (r *TransactionalWarehouseResource) Update(ctx context.Context, req resourc variables = map[string]interface{}{ "changes": client.JSONString(fmt.Sprintf( - `{"db_type":"%s", "host": "%s", "port": %d, "user": "%s", "password": "%s"}`, + `{"db_type":"%s", "host": "%s", "port": "%d", "user": "%s", "password": "%s"}`, dbType, host, port, username, password)), "connectionId": client.UUID(data.ConnectionUuid.ValueString()), "shouldReplace": true, diff --git a/internal/warehouse/transactional_warehouse_test.go b/internal/warehouse/transactional_warehouse_test.go new file mode 100644 index 0000000..79776f7 --- /dev/null +++ b/internal/warehouse/transactional_warehouse_test.go @@ -0,0 +1,113 @@ +package warehouse_test + +import ( + "fmt" + "os" + "strconv" + "testing" + + "github.com/kiwicom/terraform-provider-montecarlo/internal/acctest" + + "github.com/hashicorp/terraform-plugin-testing/config" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" +) + +func TestAccTransactionalWarehouseResource(t *testing.T) { + mc_api_key_id := os.Getenv("MC_API_KEY_ID") + mc_api_key_token := os.Getenv("MC_API_KEY_TOKEN") + collectorUuid := "a08d23fc-00a0-4c36-b568-82e9d0e67ad8" + + pgHost := os.Getenv("PG_HOST") + pgPortRaw := os.Getenv("PG_PORT") + pgPort, pgPortErr := strconv.Atoi(pgPortRaw) + pgDatabase := os.Getenv("PG_DATABASE") + pgUser := os.Getenv("PG_USER") + pgPassword := os.Getenv("PG_PASSWORD") + + if pgHost == "" { + t.Fatalf("'PG_HOST' must be set for this acceptance tests") + } else if pgPortRaw == "" || pgPortErr != nil { + t.Fatalf("'PG_PORT' (int) must be set for this acceptance tests") + } else if pgDatabase == "" { + t.Fatalf("'PG_DATABASE' must be set for this acceptance tests") + } else if pgUser == "" { + t.Fatalf("'PG_USER' must be set for this acceptance tests") + } else if pgPassword == "" { + t.Fatalf("'PG_PASSWORD' must be set for this acceptance tests") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.TestAccPreCheck(t) }, + Steps: []resource.TestStep{ + { // Create and Read testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigFile: config.TestNameFile("create.tf"), + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + "pg_host": config.StringVariable(pgHost), + "pg_port": config.IntegerVariable(pgPort), + "pg_database": config.StringVariable(pgDatabase), + "pg_user": config.StringVariable(pgUser), + "pg_password": config.StringVariable(pgPassword), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "name", "name1"), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "collector_uuid", collectorUuid), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "deletion_protection", "false"), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.host", pgHost), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.port", pgPortRaw), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.database", pgDatabase), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.username", pgUser), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.password", pgPassword), + ), + }, + { // ImportState testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + "pg_host": config.StringVariable(pgHost), + "pg_port": config.IntegerVariable(pgPort), + "pg_database": config.StringVariable(pgDatabase), + "pg_user": config.StringVariable(pgUser), + "pg_password": config.StringVariable(pgPassword), + }, + ResourceName: "montecarlo_transactional_warehouse.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: func(s *terraform.State) (string, error) { + uuid := s.RootModule().Resources["montecarlo_transactional_warehouse.test"].Primary.Attributes["uuid"] + connectionUuid := s.RootModule().Resources["montecarlo_transactional_warehouse.test"].Primary.Attributes["connection_uuid"] + return fmt.Sprintf("%[1]s,%[2]s,%[3]s", uuid, connectionUuid, collectorUuid), nil + }, + ImportStateVerifyIdentifierAttribute: "uuid", + ImportStateVerifyIgnore: []string{"db_type", "deletion_protection", "configuration"}, + }, + { // Update and Read testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigFile: config.TestNameFile("update.tf"), + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + "pg_host": config.StringVariable(pgHost), + "pg_port": config.IntegerVariable(pgPort), + "pg_database": config.StringVariable(pgDatabase), + "pg_user": config.StringVariable(pgUser), + "pg_password": config.StringVariable(pgPassword), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "name", "name1"), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "collector_uuid", collectorUuid), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "deletion_protection", "false"), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.host", pgHost), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.port", pgPortRaw), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.database", pgDatabase), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.username", pgUser), + resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.password", pgPassword), + ), + }, + }, + }) +} diff --git a/monte_carlo/data_sources/warehouse.go b/internal/warehouse/warehouse.go similarity index 96% rename from monte_carlo/data_sources/warehouse.go rename to internal/warehouse/warehouse.go index 3bc06fd..8c0f66b 100644 --- a/monte_carlo/data_sources/warehouse.go +++ b/internal/warehouse/warehouse.go @@ -1,11 +1,11 @@ -package datasources +package warehouse import ( "context" "fmt" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" + "github.com/kiwicom/terraform-provider-montecarlo/client" + "github.com/kiwicom/terraform-provider-montecarlo/internal/common" "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/datasource/schema" diff --git a/internal/warehouse/warehouse_test.go b/internal/warehouse/warehouse_test.go new file mode 100644 index 0000000..7148435 --- /dev/null +++ b/internal/warehouse/warehouse_test.go @@ -0,0 +1,50 @@ +package warehouse_test + +import ( + "fmt" + "os" + "testing" + + "github.com/kiwicom/terraform-provider-montecarlo/internal/acctest" + + "github.com/hashicorp/terraform-plugin-testing/config" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +func TestAccWarehouseDataSource(t *testing.T) { + mc_api_key_id := os.Getenv("MC_API_KEY_ID") + mc_api_key_token := os.Getenv("MC_API_KEY_TOKEN") + + project := "data-playground-8bb9fc23" + dataset := "terraform_provider_montecarlo" + personTable := "person" + deviceTable := "device" + accountUuid := "3e9abc75-5dc1-447e-b4cb-9d5a6fc5db5c" + warehouseUuid := "da6c0716-2724-4bfc-b5cc-7e0364faf979" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.TestAccPreCheck(t) }, + Steps: []resource.TestStep{ + { // Read testing + ProtoV6ProviderFactories: acctest.TestAccProviderFactories, + ConfigFile: config.TestNameFile("read.tf"), + ConfigVariables: config.Variables{ + "montecarlo_api_key_id": config.StringVariable(mc_api_key_id), + "montecarlo_api_key_token": config.StringVariable(mc_api_key_token), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "uuid", "da6c0716-2724-4bfc-b5cc-7e0364faf979"), + resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "projects.%", "1"), + resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "projects."+project+".mcon", + fmt.Sprintf("MCON++%s++%s++project++%s", accountUuid, warehouseUuid, project)), + resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "projects."+project+".datasets."+dataset+".mcon", + fmt.Sprintf("MCON++%s++%s++dataset++%s:%s", accountUuid, warehouseUuid, project, dataset)), + resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "projects."+project+".datasets."+dataset+".tables."+personTable+".mcon", + fmt.Sprintf("MCON++%s++%s++table++%s:%s.%s", accountUuid, warehouseUuid, project, dataset, personTable)), + resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "projects."+project+".datasets."+dataset+".tables."+deviceTable+".mcon", + fmt.Sprintf("MCON++%s++%s++table++%s:%s.%s", accountUuid, warehouseUuid, project, dataset, deviceTable)), + ), + }, + }, + }) +} diff --git a/main.go b/main.go index 506660a..b7097e4 100644 --- a/main.go +++ b/main.go @@ -5,7 +5,7 @@ import ( "flag" "log" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/provider" + "github.com/kiwicom/terraform-provider-montecarlo/internal" "github.com/hashicorp/terraform-plugin-framework/providerserver" ) @@ -23,7 +23,7 @@ var ( func main() { flag.Parse() opts := providerserver.ServeOpts{Address: "registry.terraform.io/kiwicom/montecarlo", Debug: false} - if err := providerserver.Serve(context.Background(), provider.New(version, nil), opts); err != nil { + if err := providerserver.Serve(context.Background(), internal.New(version), opts); err != nil { log.Fatal(err.Error()) } } diff --git a/monte_carlo/client/mock/monte_carlo_client.go b/monte_carlo/client/mock/monte_carlo_client.go deleted file mode 100644 index e0b8e66..0000000 --- a/monte_carlo/client/mock/monte_carlo_client.go +++ /dev/null @@ -1,226 +0,0 @@ -// Code generated by mockery v2.36.0. DO NOT EDIT. - -package mock - -import ( - context "context" - - graphql "github.com/hasura/go-graphql-client" - mock "github.com/stretchr/testify/mock" -) - -// MonteCarloClient is an autogenerated mock type for the MonteCarloClient type -type MonteCarloClient struct { - mock.Mock -} - -type MonteCarloClient_Expecter struct { - mock *mock.Mock -} - -func (_m *MonteCarloClient) EXPECT() *MonteCarloClient_Expecter { - return &MonteCarloClient_Expecter{mock: &_m.Mock} -} - -// ExecRaw provides a mock function with given fields: ctx, query, variables, options -func (_m *MonteCarloClient) ExecRaw(ctx context.Context, query string, variables map[string]interface{}, options ...graphql.Option) ([]byte, error) { - _va := make([]interface{}, len(options)) - for _i := range options { - _va[_i] = options[_i] - } - var _ca []interface{} - _ca = append(_ca, ctx, query, variables) - _ca = append(_ca, _va...) - ret := _m.Called(_ca...) - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, map[string]interface{}, ...graphql.Option) ([]byte, error)); ok { - return rf(ctx, query, variables, options...) - } - if rf, ok := ret.Get(0).(func(context.Context, string, map[string]interface{}, ...graphql.Option) []byte); ok { - r0 = rf(ctx, query, variables, options...) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, string, map[string]interface{}, ...graphql.Option) error); ok { - r1 = rf(ctx, query, variables, options...) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// MonteCarloClient_ExecRaw_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecRaw' -type MonteCarloClient_ExecRaw_Call struct { - *mock.Call -} - -// ExecRaw is a helper method to define mock.On call -// - ctx context.Context -// - query string -// - variables map[string]interface{} -// - options ...graphql.Option -func (_e *MonteCarloClient_Expecter) ExecRaw(ctx interface{}, query interface{}, variables interface{}, options ...interface{}) *MonteCarloClient_ExecRaw_Call { - return &MonteCarloClient_ExecRaw_Call{Call: _e.mock.On("ExecRaw", - append([]interface{}{ctx, query, variables}, options...)...)} -} - -func (_c *MonteCarloClient_ExecRaw_Call) Run(run func(ctx context.Context, query string, variables map[string]interface{}, options ...graphql.Option)) *MonteCarloClient_ExecRaw_Call { - _c.Call.Run(func(args mock.Arguments) { - variadicArgs := make([]graphql.Option, len(args)-3) - for i, a := range args[3:] { - if a != nil { - variadicArgs[i] = a.(graphql.Option) - } - } - run(args[0].(context.Context), args[1].(string), args[2].(map[string]interface{}), variadicArgs...) - }) - return _c -} - -func (_c *MonteCarloClient_ExecRaw_Call) Return(_a0 []byte, _a1 error) *MonteCarloClient_ExecRaw_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *MonteCarloClient_ExecRaw_Call) RunAndReturn(run func(context.Context, string, map[string]interface{}, ...graphql.Option) ([]byte, error)) *MonteCarloClient_ExecRaw_Call { - _c.Call.Return(run) - return _c -} - -// Mutate provides a mock function with given fields: ctx, m, variables, options -func (_m *MonteCarloClient) Mutate(ctx context.Context, m interface{}, variables map[string]interface{}, options ...graphql.Option) error { - _va := make([]interface{}, len(options)) - for _i := range options { - _va[_i] = options[_i] - } - var _ca []interface{} - _ca = append(_ca, ctx, m, variables) - _ca = append(_ca, _va...) - ret := _m.Called(_ca...) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, interface{}, map[string]interface{}, ...graphql.Option) error); ok { - r0 = rf(ctx, m, variables, options...) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MonteCarloClient_Mutate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Mutate' -type MonteCarloClient_Mutate_Call struct { - *mock.Call -} - -// Mutate is a helper method to define mock.On call -// - ctx context.Context -// - m interface{} -// - variables map[string]interface{} -// - options ...graphql.Option -func (_e *MonteCarloClient_Expecter) Mutate(ctx interface{}, m interface{}, variables interface{}, options ...interface{}) *MonteCarloClient_Mutate_Call { - return &MonteCarloClient_Mutate_Call{Call: _e.mock.On("Mutate", - append([]interface{}{ctx, m, variables}, options...)...)} -} - -func (_c *MonteCarloClient_Mutate_Call) Run(run func(ctx context.Context, m interface{}, variables map[string]interface{}, options ...graphql.Option)) *MonteCarloClient_Mutate_Call { - _c.Call.Run(func(args mock.Arguments) { - variadicArgs := make([]graphql.Option, len(args)-3) - for i, a := range args[3:] { - if a != nil { - variadicArgs[i] = a.(graphql.Option) - } - } - run(args[0].(context.Context), args[1].(interface{}), args[2].(map[string]interface{}), variadicArgs...) - }) - return _c -} - -func (_c *MonteCarloClient_Mutate_Call) Return(_a0 error) *MonteCarloClient_Mutate_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *MonteCarloClient_Mutate_Call) RunAndReturn(run func(context.Context, interface{}, map[string]interface{}, ...graphql.Option) error) *MonteCarloClient_Mutate_Call { - _c.Call.Return(run) - return _c -} - -// Query provides a mock function with given fields: ctx, q, variables, options -func (_m *MonteCarloClient) Query(ctx context.Context, q interface{}, variables map[string]interface{}, options ...graphql.Option) error { - _va := make([]interface{}, len(options)) - for _i := range options { - _va[_i] = options[_i] - } - var _ca []interface{} - _ca = append(_ca, ctx, q, variables) - _ca = append(_ca, _va...) - ret := _m.Called(_ca...) - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, interface{}, map[string]interface{}, ...graphql.Option) error); ok { - r0 = rf(ctx, q, variables, options...) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// MonteCarloClient_Query_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Query' -type MonteCarloClient_Query_Call struct { - *mock.Call -} - -// Query is a helper method to define mock.On call -// - ctx context.Context -// - q interface{} -// - variables map[string]interface{} -// - options ...graphql.Option -func (_e *MonteCarloClient_Expecter) Query(ctx interface{}, q interface{}, variables interface{}, options ...interface{}) *MonteCarloClient_Query_Call { - return &MonteCarloClient_Query_Call{Call: _e.mock.On("Query", - append([]interface{}{ctx, q, variables}, options...)...)} -} - -func (_c *MonteCarloClient_Query_Call) Run(run func(ctx context.Context, q interface{}, variables map[string]interface{}, options ...graphql.Option)) *MonteCarloClient_Query_Call { - _c.Call.Run(func(args mock.Arguments) { - variadicArgs := make([]graphql.Option, len(args)-3) - for i, a := range args[3:] { - if a != nil { - variadicArgs[i] = a.(graphql.Option) - } - } - run(args[0].(context.Context), args[1].(interface{}), args[2].(map[string]interface{}), variadicArgs...) - }) - return _c -} - -func (_c *MonteCarloClient_Query_Call) Return(_a0 error) *MonteCarloClient_Query_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *MonteCarloClient_Query_Call) RunAndReturn(run func(context.Context, interface{}, map[string]interface{}, ...graphql.Option) error) *MonteCarloClient_Query_Call { - _c.Call.Return(run) - return _c -} - -// NewMonteCarloClient creates a new instance of MonteCarloClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMonteCarloClient(t interface { - mock.TestingT - Cleanup(func()) -}) *MonteCarloClient { - mock := &MonteCarloClient{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/monte_carlo/data_sources/warehouse_test.go b/monte_carlo/data_sources/warehouse_test.go deleted file mode 100644 index 231e341..0000000 --- a/monte_carlo/data_sources/warehouse_test.go +++ /dev/null @@ -1,110 +0,0 @@ -package datasources_test - -import ( - "fmt" - "testing" - - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - cmock "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client/mock" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/provider" - "github.com/stretchr/testify/mock" - - "github.com/hashicorp/terraform-plugin-framework/providerserver" - "github.com/hashicorp/terraform-plugin-go/tfprotov6" - "github.com/hashicorp/terraform-plugin-testing/helper/resource" -) - -func TestAccWarehouseDataSource(t *testing.T) { - accountUuid := "a84380ed-b962-4bd3-b150-04bc38a209d5++e7c59fd6" - warehouseUuid := "427a1600-2653-40c5-a1e7-5ec98703ee9d" - project1 := "bi-prod" - project2 := "booking" - dataset1 := "raw" - dataset2 := "processed" - table1 := "events" - table2 := "pageHits" - assignment1 := fmt.Sprintf("MCON++a84380ed-b962-4bd3-b150-04bc38a209d5++427a1600-2653-40c5-a1e7-5ec98703ee9d++table++%s:%s.%s", - project1, dataset1, table1) - assignment2 := fmt.Sprintf("MCON++a84380ed-b962-4bd3-b150-04bc38a209d5++e7c59fd6-7ca8-41e7-8325-062ea38d3df5++table++%s:%s.%s", - project2, dataset2, table2) - - providerContext := &common.ProviderContext{MonteCarloClient: initWarehouseMonteCarloClient( - warehouseUuid, accountUuid, assignment1, assignment2, project1, project2, - dataset1, dataset2, table1, table2, - )} - providerFactories := map[string]func() (tfprotov6.ProviderServer, error){ - "montecarlo": providerserver.NewProtocol6WithError(provider.New("test", providerContext)()), - } - - resource.Test(t, resource.TestCase{ - PreCheck: func() {}, - ProtoV6ProviderFactories: providerFactories, - Steps: []resource.TestStep{ - { // Read testing - Config: warehouseConfig(warehouseUuid), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "uuid", warehouseUuid), - resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "projects.%", "2"), - resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "projects."+project1+".mcon", - fmt.Sprintf("MCON++%s++%s++project++%s", accountUuid, warehouseUuid, project1)), - resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "projects."+project2+".mcon", - fmt.Sprintf("MCON++%s++%s++project++%s", accountUuid, warehouseUuid, project2)), - resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "projects."+project1+".datasets."+dataset1+".mcon", - fmt.Sprintf("MCON++%s++%s++dataset++%s:%s", accountUuid, warehouseUuid, project1, dataset1)), - resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "projects."+project2+".datasets."+dataset2+".mcon", - fmt.Sprintf("MCON++%s++%s++dataset++%s:%s", accountUuid, warehouseUuid, project2, dataset2)), - resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "projects."+project1+".datasets."+dataset1+".tables."+table1+".mcon", assignment1), - resource.TestCheckResourceAttr("data.montecarlo_warehouse.test", "projects."+project2+".datasets."+dataset2+".tables."+table2+".mcon", assignment2), - ), - }, - }, - }) -} - -func warehouseConfig(uuid string) string { - return fmt.Sprintf(` -provider "montecarlo" { - account_service_key = { - id = "montecarlo" - token = "montecarlo" - } -} - -data "montecarlo_warehouse" "test" { - uuid = %[1]q -} -`, uuid) -} - -func initWarehouseMonteCarloClient( - warehouseUuid, accountUuid, assignment1, assignment2, - project1, project2, dataset1, dataset2, table1, table2 string) client.MonteCarloClient { - mcClient := cmock.MonteCarloClient{} - mcClient.On("Query", mock.Anything, mock.AnythingOfType("*client.GetTables"), mock.MatchedBy(func(in map[string]interface{}) bool { - return in["dwId"] == client.UUID(warehouseUuid) && - in["isDeleted"] == false && in["isExcluded"] == false - })).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.GetTables) - arg.GetTables.PageInfo.HasNextPage = false - - edge1 := client.GetTablesEdge{} - edge1.Node.Mcon = assignment1 - edge1.Node.ProjectName = project1 - edge1.Node.Dataset = dataset1 - edge1.Node.TableId = table1 - edge1.Node.Warehouse.Uuid = warehouseUuid - edge1.Node.Warehouse.Account.Uuid = accountUuid - - edge2 := client.GetTablesEdge{} - edge2.Node.Mcon = assignment2 - edge2.Node.ProjectName = project2 - edge2.Node.Dataset = dataset2 - edge2.Node.TableId = table2 - edge2.Node.Warehouse.Uuid = warehouseUuid - edge2.Node.Warehouse.Account.Uuid = accountUuid - - arg.GetTables.Edges = append(arg.GetTables.Edges, edge1, edge2) - }) - return &mcClient -} diff --git a/monte_carlo/provider/provider_test.go b/monte_carlo/provider/provider_test.go deleted file mode 100644 index 67d5301..0000000 --- a/monte_carlo/provider/provider_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package provider_test - -import ( - "testing" - - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/provider" - - "github.com/hashicorp/terraform-plugin-framework/providerserver" - "github.com/hashicorp/terraform-plugin-go/tfprotov6" -) - -// testAccProtoV6ProviderFactories are used to instantiate a provider during -// acceptance testing. The factory function will be invoked for every Terraform -// CLI command executed to create a provider server to which the CLI can -// reattach. -var providerFactories = map[string]func() (tfprotov6.ProviderServer, error){ - "montecarlo": providerserver.NewProtocol6WithError(provider.New("test", nil)()), -} - -func TestAccPreCheck(t *testing.T) { - // You can add code here to run prior to any test case execution, for example assertions - // about the appropriate environment variables being set are common to see in a pre-check - // function. -} diff --git a/monte_carlo/resources/bigquery_warehouse_test.go b/monte_carlo/resources/bigquery_warehouse_test.go deleted file mode 100644 index c3f5630..0000000 --- a/monte_carlo/resources/bigquery_warehouse_test.go +++ /dev/null @@ -1,128 +0,0 @@ -package resources_test - -import ( - "fmt" - "testing" - - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - cmock "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client/mock" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/provider" - "github.com/stretchr/testify/mock" - - "github.com/hashicorp/terraform-plugin-framework/providerserver" - "github.com/hashicorp/terraform-plugin-go/tfprotov6" - "github.com/hashicorp/terraform-plugin-testing/helper/resource" -) - -func TestAccBigQueryWarehouseResource(t *testing.T) { - providerContext := &common.ProviderContext{MonteCarloClient: initBigQueryWarehouseMonteCarloClient()} - providerFactories := map[string]func() (tfprotov6.ProviderServer, error){ - "montecarlo": providerserver.NewProtocol6WithError(provider.New("test", providerContext)()), - } - - resource.Test(t, resource.TestCase{ - PreCheck: func() {}, - ProtoV6ProviderFactories: providerFactories, - Steps: []resource.TestStep{ - { // Create and Read testing - Config: bigQueryWarehouseConfig("name1", "dataCollector1", "{}"), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "uuid", "8bfc4"), - resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "connection_uuid", "8cd5a"), - resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "name", "name1"), - resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "collector_uuid", "dataCollector1"), - resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "service_account_key", "{}"), - resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "deletion_protection", "false"), - ), - }, - { // ImportState testing - ResourceName: "montecarlo_bigquery_warehouse.test", - ImportState: true, - ImportStateVerify: true, - ImportStateId: "8bfc4,8cd5a,dataCollector1", - ImportStateVerifyIdentifierAttribute: "uuid", - ImportStateVerifyIgnore: []string{"deletion_protection", "service_account_key"}, - }, - // Update and Read testing - { - Config: bigQueryWarehouseConfig("name2", "dataCollector1", "{\"json\": \"json\"}"), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "uuid", "8bfc4"), - resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "connection_uuid", "8cd5a"), - resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "name", "name2"), - resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "collector_uuid", "dataCollector1"), - resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "service_account_key", "{\"json\": \"json\"}"), - resource.TestCheckResourceAttr("montecarlo_bigquery_warehouse.test", "deletion_protection", "false"), - ), - }, - }, - }) -} - -func bigQueryWarehouseConfig(name string, dcid string, saKey string) string { - return fmt.Sprintf(` -provider "montecarlo" { - account_service_key = { - id = "montecarlo" - token = "montecarlo" - } -} - -resource "montecarlo_bigquery_warehouse" "test" { - name = %[1]q - collector_uuid = %[2]q - service_account_key = %[3]q - deletion_protection = false -} -`, name, dcid, saKey) -} - -func initBigQueryWarehouseMonteCarloClient() client.MonteCarloClient { - mcClient := cmock.MonteCarloClient{} - // Add connection operations - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.TestBqCredentialsV2"), mock.Anything).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.TestBqCredentialsV2) - arg.TestBqCredentialsV2.Key = "testKey" - arg.TestBqCredentialsV2.ValidationResult.Success = true - arg.TestBqCredentialsV2.ValidationResult.Errors = client.BqTestErrors{} - arg.TestBqCredentialsV2.ValidationResult.Warnings = client.BqTestWarnings{} - }) - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.AddConnection"), mock.Anything).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.AddConnection) - arg.AddConnection.Connection.Uuid = "8cd5a" - arg.AddConnection.Connection.Warehouse.Uuid = "8bfc4" - arg.AddConnection.Connection.Warehouse.Name = "name1" - }) - - // Read operations - readVariables1 := map[string]interface{}{"uuid": client.UUID("8bfc4")} - readResponse1 := []byte(fmt.Sprintf(`{"getWarehouse":{"name":"name1","connections":[{"uuid":"8cd5a",`+ - `"type":"%s"}],"dataCollector":{"uuid":"dataCollector1"}}}`, client.BigQueryConnectionTypeResponse)) - mcClient.On("ExecRaw", mock.Anything, client.GetWarehouseQuery, readVariables1).Return(readResponse1, nil) - - // Delete operations - deleteVariables2 := map[string]interface{}{"connectionId": client.UUID("8cd5a")} - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.RemoveConnection"), deleteVariables2).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.RemoveConnection) - arg.RemoveConnection.Success = true - }) - - // Update operations - updateVariables := map[string]interface{}{"dwId": client.UUID("8bfc4"), "name": "name2"} - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.SetWarehouseName"), updateVariables).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.SetWarehouseName) - arg.SetWarehouseName.Warehouse.Uuid = "8bfc4" - arg.SetWarehouseName.Warehouse.Name = "name2" - }) - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.UpdateCredentials"), mock.Anything).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.UpdateCredentials) - arg.UpdateCredentials.Success = true - // after update, read operation must return new results - mcClient.On("ExecRaw", mock.Anything, client.GetWarehouseQuery, readVariables1).Unset() - readResponse := []byte(fmt.Sprintf(`{"getWarehouse":{"name":"name2","connections":[{"uuid":"8cd5a",`+ - `"type":"%s"}],"dataCollector":{"uuid":"dataCollector1"}}}`, client.BigQueryConnectionTypeResponse)) - mcClient.On("ExecRaw", mock.Anything, client.GetWarehouseQuery, readVariables1).Return(readResponse, nil) - }) - return &mcClient -} diff --git a/monte_carlo/resources/domain_test.go b/monte_carlo/resources/domain_test.go deleted file mode 100644 index d9b3446..0000000 --- a/monte_carlo/resources/domain_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package resources_test - -import ( - "fmt" - "testing" - - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - cmock "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client/mock" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/provider" - "github.com/stretchr/testify/mock" - - "github.com/hashicorp/terraform-plugin-framework/providerserver" - "github.com/hashicorp/terraform-plugin-go/tfprotov6" - "github.com/hashicorp/terraform-plugin-testing/helper/resource" -) - -func TestAccDomainResource(t *testing.T) { - domainUuid := "8bfc4" - domainName1 := "domain1" - domainName2 := "domain2" - assignment1 := "MCON++a84380ed-b962-4bd3-b150-04bc38a209d5++427a1600-2653-40c5-a1e7-5ec98703ee9d++project++gcp-project1-722af1c6" - assignment2 := "MCON++a84380ed-b962-4bd3-b150-04bc38a209d5++e7c59fd6-7ca8-41e7-8325-062ea38d3df5++dataset++postgre-dataset-1" - - providerContext := &common.ProviderContext{MonteCarloClient: initDomainMonteCarloClient( - domainUuid, domainName1, domainName2, assignment1, assignment2, - )} - providerFactories := map[string]func() (tfprotov6.ProviderServer, error){ - "montecarlo": providerserver.NewProtocol6WithError(provider.New("test", providerContext)()), - } - - resource.Test(t, resource.TestCase{ - PreCheck: func() {}, - ProtoV6ProviderFactories: providerFactories, - Steps: []resource.TestStep{ - { // Create and Read testing - Config: domainConfig(domainName1, "Domain test description"), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("montecarlo_domain.test", "uuid", domainUuid), - resource.TestCheckResourceAttr("montecarlo_domain.test", "name", domainName1), - resource.TestCheckResourceAttr("montecarlo_domain.test", "description", "Domain test description"), - resource.TestCheckResourceAttr("montecarlo_domain.test", "assignments.#", "0"), - resource.TestCheckResourceAttr("montecarlo_domain.test", "tags.#", "2"), - resource.TestCheckTypeSetElemNestedAttrs("montecarlo_domain.test", "tags.*", map[string]string{ - "name": "dataset_tables_1", - }), - resource.TestCheckTypeSetElemNestedAttrs("montecarlo_domain.test", "tags.*", map[string]string{ - "name": "owner", - "value": "bi-internal", - }), - ), - }, - { // ImportState testing - ResourceName: "montecarlo_domain.test", - ImportState: true, - ImportStateVerify: true, - ImportStateId: domainUuid, - ImportStateVerifyIdentifierAttribute: "uuid", - }, - // Update and Read testing - { - Config: domainConfigUpdate(domainName2, "Domain test description"), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("montecarlo_domain.test", "uuid", domainUuid), - resource.TestCheckResourceAttr("montecarlo_domain.test", "name", domainName2), - resource.TestCheckResourceAttr("montecarlo_domain.test", "description", "Domain test description"), - resource.TestCheckResourceAttr("montecarlo_domain.test", "assignments.#", "2"), - resource.TestCheckResourceAttr("montecarlo_domain.test", "tags.#", "0"), - resource.TestCheckTypeSetElemAttr("montecarlo_domain.test", "assignments.*", assignment1), - resource.TestCheckTypeSetElemAttr("montecarlo_domain.test", "assignments.*", assignment2), - ), - }, - }}, - ) -} - -func domainConfig(name string, description string) string { - return fmt.Sprintf(` -provider "montecarlo" { - account_service_key = { - id = "montecarlo" - token = "montecarlo" - } -} - -resource "montecarlo_domain" "test" { - name = %[1]q - description = %[2]q - tags = [ - { - name = "owner" - value = "bi-internal" - }, - { - name = "dataset_tables_1" - } - ] -} -`, name, description) -} - -func domainConfigUpdate(name string, description string) string { - return fmt.Sprintf(` -provider "montecarlo" { - account_service_key = { - id = "montecarlo" - token = "montecarlo" - } -} - -resource "montecarlo_domain" "test" { - name = %[1]q - description = %[2]q - assignments = [ - "MCON++a84380ed-b962-4bd3-b150-04bc38a209d5++427a1600-2653-40c5-a1e7-5ec98703ee9d++project++gcp-project1-722af1c6", - "MCON++a84380ed-b962-4bd3-b150-04bc38a209d5++e7c59fd6-7ca8-41e7-8325-062ea38d3df5++dataset++postgre-dataset-1" - ] -} -`, name, description) -} - -func initDomainMonteCarloClient(domainUuid, domainName1, domainName2, assignment1, assignment2 string) client.MonteCarloClient { - mcClient := cmock.MonteCarloClient{} - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.CreateOrUpdateDomain"), mock.MatchedBy(func(in map[string]interface{}) bool { - return in["uuid"] == (*client.UUID)(nil) && - in["name"] == domainName1 && - in["description"] == "Domain test description" - })).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.CreateOrUpdateDomain) - arg.CreateOrUpdateDomain.Domain.Uuid = domainUuid - arg.CreateOrUpdateDomain.Domain.Name = domainName1 - arg.CreateOrUpdateDomain.Domain.Description = "Domain test description" - arg.CreateOrUpdateDomain.Domain.Assignments = []string{} - arg.CreateOrUpdateDomain.Domain.Tags = []client.TagKeyValuePairOutput{ - {Name: "owner", Value: "bi-internal"}, - {Name: "dataset_tables_1"}, - } - }) - - readVariables1 := map[string]interface{}{"uuid": client.UUID(domainUuid)} - tagsResponse := `"tags":[{"name":"owner","value":"bi-internal"},{"name":"dataset_tables_1"}]` - readResponse1 := []byte(`{"getDomain":{"uuid":"` + domainUuid + `","name":"` + domainName1 + `","description":"Domain test description","assignments":[],` + tagsResponse + `}}`) - mcClient.On("ExecRaw", mock.Anything, client.GetDomainQuery, readVariables1).Return(readResponse1, nil) - - deleteVariables1 := map[string]interface{}{"uuid": client.UUID(domainUuid)} - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.DeleteDomain"), deleteVariables1).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.DeleteDomain) - arg.DeleteDomain.Deleted = 1 - }) - - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.CreateOrUpdateDomain"), mock.MatchedBy(func(in map[string]interface{}) bool { - return in["uuid"] == client.UUID(domainUuid) && - in["name"] == domainName2 && - in["description"] == "Domain test description" - })).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.CreateOrUpdateDomain) - arg.CreateOrUpdateDomain.Domain.Uuid = domainUuid - arg.CreateOrUpdateDomain.Domain.Name = domainName2 - arg.CreateOrUpdateDomain.Domain.Description = "Domain test description" - arg.CreateOrUpdateDomain.Domain.Tags = []client.TagKeyValuePairOutput{} - arg.CreateOrUpdateDomain.Domain.Assignments = []string{assignment1, assignment2} - - mcClient.On("ExecRaw", mock.Anything, client.GetDomainQuery, readVariables1).Unset() - assignmentsResponse := `"assignments":["` + assignment1 + `","` + assignment2 + `"]` - readResponse2 := []byte(`{"getDomain":{"uuid":"` + domainUuid + `","name":"` + domainName2 + `","description":"Domain test description","tags":[],` + assignmentsResponse + `}}`) - mcClient.On("ExecRaw", mock.Anything, client.GetDomainQuery, readVariables1).Return(readResponse2, nil) - }) - return &mcClient -} diff --git a/monte_carlo/resources/iam_group_test.go b/monte_carlo/resources/iam_group_test.go deleted file mode 100644 index 942f9f6..0000000 --- a/monte_carlo/resources/iam_group_test.go +++ /dev/null @@ -1,189 +0,0 @@ -package resources_test - -import ( - "fmt" - "slices" - "strings" - "testing" - - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - cmock "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client/mock" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/provider" - - "github.com/hashicorp/terraform-plugin-framework/providerserver" - "github.com/hashicorp/terraform-plugin-go/tfprotov6" - "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/stretchr/testify/mock" -) - -func TestAccIamGroupResource(t *testing.T) { - name := "group-1" - role := "mcd/editor" - roleUpdate := "mcd/owner" - domainsUpdate := []string{"domain1", "domain2"} - ssoGroupUpdate := "ssoGroup1" - - providerContext := &common.ProviderContext{MonteCarloClient: initIamGroupMonteCarloClient( - name, role, roleUpdate, ssoGroupUpdate, domainsUpdate, - )} - providerFactories := map[string]func() (tfprotov6.ProviderServer, error){ - "montecarlo": providerserver.NewProtocol6WithError(provider.New("test", providerContext)()), - } - - resource.Test(t, resource.TestCase{ - PreCheck: func() {}, - ProtoV6ProviderFactories: providerFactories, - Steps: []resource.TestStep{ - { // Create and Read testing - Config: iamGroupConfig(name, role, nil, nil), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("montecarlo_iam_group.test", "name", name), - resource.TestCheckResourceAttr("montecarlo_iam_group.test", "label", name), - resource.TestCheckResourceAttr("montecarlo_iam_group.test", "description", ""), - resource.TestCheckResourceAttr("montecarlo_iam_group.test", "role", role), - resource.TestCheckResourceAttr("montecarlo_iam_group.test", "domains.#", "0"), - resource.TestCheckNoResourceAttr("montecarlo_iam_group.test", "ssoGroup"), - ), - }, - { // ImportState testing - ResourceName: "montecarlo_iam_group.test", - ImportState: true, - ImportStateVerify: true, - ImportStateId: name, - ImportStateVerifyIdentifierAttribute: "name", - }, - { // Update and Read testing - Config: iamGroupConfig(name, roleUpdate, &domainsUpdate, &ssoGroupUpdate), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("montecarlo_iam_group.test", "name", name), - resource.TestCheckResourceAttr("montecarlo_iam_group.test", "label", name), - resource.TestCheckResourceAttr("montecarlo_iam_group.test", "description", ""), - resource.TestCheckResourceAttr("montecarlo_iam_group.test", "role", roleUpdate), - resource.TestCheckResourceAttr("montecarlo_iam_group.test", "domains.#", "2"), - resource.TestCheckTypeSetElemAttr("montecarlo_iam_group.test", "domains.*", domainsUpdate[0]), - resource.TestCheckTypeSetElemAttr("montecarlo_iam_group.test", "domains.*", domainsUpdate[1]), - resource.TestCheckResourceAttr("montecarlo_iam_group.test", "sso_group", ssoGroupUpdate), - ), - }, - }, - }) -} - -func iamGroupConfig(name string, role string, domainRestrictions *[]string, ssoGroup *string) string { - domainRestrictionsConfig := "" - ssoGroupConfig := "" - if domainRestrictions != nil { - domainRestrictionsConfig = fmt.Sprintf("domains = %s", strings.Join( - strings.Split(fmt.Sprintf("%q", *domainRestrictions), " "), - ", "), - ) - } - if ssoGroup != nil { - ssoGroupConfig = fmt.Sprintf("sso_group = %q", *ssoGroup) - } - return fmt.Sprintf(` -provider "montecarlo" { - account_service_key = { - id = "montecarlo" - token = "montecarlo" - } -} - -resource "montecarlo_iam_group" "test" { - name = %[1]q - role = %[2]q - %[3]s - %[4]s -} -`, name, role, domainRestrictionsConfig, ssoGroupConfig) -} - -func initIamGroupMonteCarloClient(name, role, roleUpdate, ssoGroupUpdate string, domainsUpdate []string) client.MonteCarloClient { - mcClient := cmock.MonteCarloClient{} - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.CreateOrUpdateAuthorizationGroup"), mock.MatchedBy(func(in map[string]interface{}) bool { - roles, rolesOk := in["roles"].([]string) - domainRestrictions, domainRestrictionsOk := in["domainRestrictionIds"].([]client.UUID) - return in["name"] == name && - in["label"] == name && - in["description"] == "" && - rolesOk && len(roles) == 1 && roles[0] == role && - domainRestrictionsOk && len(domainRestrictions) == 0 && - in["ssoGroup"] == (*string)(nil) - })).Return(nil).Run(func(args mock.Arguments) { - createResult := args.Get(1).(*client.CreateOrUpdateAuthorizationGroup) - createResult.CreateOrUpdateAuthorizationGroup.AuthorizationGroup = client.AuthorizationGroup{ - Name: name, - Label: name, - Description: "", - Roles: []struct{ Name string }{{Name: role}}, - DomainRestrictions: []struct{ Uuid string }{}, - SsoGroup: (nil), - } - }) - - mcClient.On("Query", mock.Anything, mock.AnythingOfType("*client.GetAuthorizationGroups"), mock.Anything).Return(nil).Run(func(args mock.Arguments) { - getResult := args.Get(1).(*client.GetAuthorizationGroups) - getResult.GetAuthorizationGroups = []client.AuthorizationGroup{ - { - Name: name, - Label: name, - Description: "", - Roles: []struct{ Name string }{{Name: role}}, - DomainRestrictions: []struct{ Uuid string }{}, - SsoGroup: nil, - }, - } - }) - - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.DeleteAuthorizationGroup"), mock.MatchedBy(func(in map[string]interface{}) bool { - return in["name"] == name - })).Return(nil).Run(func(args mock.Arguments) { - deleteResult := args.Get(1).(*client.DeleteAuthorizationGroup) - deleteResult.DeleteAuthorizationGroup.Deleted = 1 - }) - - // update testing - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.CreateOrUpdateAuthorizationGroup"), mock.MatchedBy(func(in map[string]interface{}) bool { - roles, rolesOk := in["roles"].([]string) - ssoGroup, ssoGroupOk := in["ssoGroup"].(*string) - domainRestrictions, domainRestrictionsOk := in["domainRestrictionIds"].([]client.UUID) - return in["name"] == name && - in["label"] == name && - in["description"] == "" && - rolesOk && len(roles) == 1 && roles[0] == roleUpdate && - domainRestrictionsOk && len(domainRestrictions) == 2 && - slices.Contains(domainRestrictions, client.UUID(domainsUpdate[0])) && - slices.Contains(domainRestrictions, client.UUID(domainsUpdate[1])) && - ssoGroupOk && *ssoGroup == ssoGroupUpdate - })).Return(nil).Run(func(args mock.Arguments) { - createResult := args.Get(1).(*client.CreateOrUpdateAuthorizationGroup) - createResult.CreateOrUpdateAuthorizationGroup.AuthorizationGroup = client.AuthorizationGroup{ - Name: name, - Label: name, - Description: "", - Roles: []struct{ Name string }{{Name: roleUpdate}}, - DomainRestrictions: []struct{ Uuid string }{{Uuid: domainsUpdate[0]}, {domainsUpdate[1]}}, - SsoGroup: &ssoGroupUpdate, - } - - // Read query will response with different result after update operation - mcClient.ExpectedCalls = slices.DeleteFunc(mcClient.ExpectedCalls, func(call *mock.Call) bool { - return call.Arguments.Is(mock.Anything, mock.AnythingOfType("*client.GetAuthorizationGroups"), mock.Anything) - }) - mcClient.On("Query", mock.Anything, mock.AnythingOfType("*client.GetAuthorizationGroups"), mock.Anything).Return(nil).Run(func(args mock.Arguments) { - getResult := args.Get(1).(*client.GetAuthorizationGroups) - getResult.GetAuthorizationGroups = []client.AuthorizationGroup{ - { - Name: name, - Label: name, - Description: "", - Roles: []struct{ Name string }{{Name: roleUpdate}}, - DomainRestrictions: []struct{ Uuid string }{{Uuid: domainsUpdate[0]}, {domainsUpdate[1]}}, - SsoGroup: &ssoGroupUpdate, - }, - } - }) - }) - return &mcClient -} diff --git a/monte_carlo/resources/iam_member_test.go b/monte_carlo/resources/iam_member_test.go deleted file mode 100644 index 53f7cc6..0000000 --- a/monte_carlo/resources/iam_member_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package resources_test - -import ( - "fmt" - "slices" - "testing" - - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - cmock "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client/mock" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/provider" - - "github.com/hashicorp/terraform-plugin-framework/providerserver" - "github.com/hashicorp/terraform-plugin-go/tfprotov6" - "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/stretchr/testify/mock" -) - -func TestAccIamMemberResource(t *testing.T) { - groupName := "group1" - memberEmail := "user1" - memberId := "123" - groupNameUpdated := "group2" - - providerContext := &common.ProviderContext{MonteCarloClient: initIamMemberMonteCarloClient( - groupName, groupNameUpdated, memberEmail, memberId, - )} - providerFactories := map[string]func() (tfprotov6.ProviderServer, error){ - "montecarlo": providerserver.NewProtocol6WithError(provider.New("test", providerContext)()), - } - - resource.Test(t, resource.TestCase{ - PreCheck: func() {}, - ProtoV6ProviderFactories: providerFactories, - Steps: []resource.TestStep{ - { // Create and Read testing - Config: iamMemberConfig(groupName, memberEmail), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("montecarlo_iam_member.test", "group", fmt.Sprintf("groups/%s", groupName)), - resource.TestCheckResourceAttr("montecarlo_iam_member.test", "member", fmt.Sprintf("user:%s", memberEmail)), - resource.TestCheckResourceAttr("montecarlo_iam_member.test", "member_id", memberId), - ), - }, - { // ImportState testing - ResourceName: "montecarlo_iam_member.test", - ImportState: true, - ImportStateVerify: true, - ImportStateId: fmt.Sprintf("groups/%[1]s,user:%[2]s", groupName, memberEmail), - ImportStateVerifyIdentifierAttribute: "group", - }, - { // Update and Read testing - Config: iamMemberConfig(groupNameUpdated, memberEmail), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("montecarlo_iam_member.test", "group", fmt.Sprintf("groups/%s", groupNameUpdated)), - resource.TestCheckResourceAttr("montecarlo_iam_member.test", "member", fmt.Sprintf("user:%s", memberEmail)), - resource.TestCheckResourceAttr("montecarlo_iam_member.test", "member_id", memberId), - ), - }, - }, - }) -} - -func iamMemberConfig(groupName, memberEmail string) string { - return fmt.Sprintf(` -provider "montecarlo" { - account_service_key = { - id = "montecarlo" - token = "montecarlo" - } -} - -resource "montecarlo_iam_member" "test" { - group = "groups/%[1]s" - member = "user:%[2]s" -} -`, groupName, memberEmail) -} - -func initIamMemberMonteCarloClient(groupName, groupNameUpdated, memberEmail, memberId string) client.MonteCarloClient { - mcClient := cmock.MonteCarloClient{} - readUser := mcClient.On("Query", mock.Anything, mock.AnythingOfType("*client.GetUsersInAccount"), mock.MatchedBy(func(in map[string]interface{}) bool { - return in["email"] == memberEmail && in["after"] == (*string)(nil) - })).Return(nil).Run(func(args mock.Arguments) { - getResult := args.Get(1).(*client.GetUsersInAccount) - getResult.GetUsersInAccount.Edges = []struct{ Node client.User }{ - {Node: client.User{CognitoUserId: memberId, IsSso: false, Email: memberEmail}}, - } - }) - - mcClient.On("Query", mock.Anything, mock.AnythingOfType("*client.GetAuthorizationGroups"), mock.Anything).Return(nil).Run(func(args mock.Arguments) { - getResult := args.Get(1).(*client.GetAuthorizationGroups) - getResult.GetAuthorizationGroups = []client.AuthorizationGroup{{ - Name: groupName, - Label: groupName, - Description: "", - Roles: []struct{ Name string }{{Name: "mcd/owner"}}, - DomainRestrictions: []struct{ Uuid string }{}, - SsoGroup: nil, - }, { - Name: groupNameUpdated, - Label: groupNameUpdated, - Description: "", - Roles: []struct{ Name string }{{Name: "mcd/owner"}}, - DomainRestrictions: []struct{ Uuid string }{}, - SsoGroup: nil, - }} - }) - - // create operation - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.UpdateUserAuthorizationGroupMembership"), mock.MatchedBy(func(in map[string]interface{}) bool { - groupNames, groupNamesOk := in["groupNames"].([]string) - return in["memberUserId"] == memberId && groupNamesOk && len(groupNames) == 1 && groupNames[0] == groupName - })).Return(nil).Run(func(args mock.Arguments) { - mcClient.ExpectedCalls = slices.DeleteFunc(mcClient.ExpectedCalls, func(call *mock.Call) bool { return call.Arguments.Is(readUser.Arguments...) }) - readUser = mcClient.On("Query", mock.Anything, mock.AnythingOfType("*client.GetUsersInAccount"), mock.MatchedBy(func(in map[string]interface{}) bool { - return in["email"] == memberEmail && in["after"] == (*string)(nil) - })).Return(nil).Run(func(args mock.Arguments) { - getResult := args.Get(1).(*client.GetUsersInAccount) - node := client.User{CognitoUserId: memberId, IsSso: false, Email: memberEmail} - node.Auth.Groups = []string{groupName} - getResult.GetUsersInAccount.Edges = []struct{ Node client.User }{{Node: node}} - }) - }) - - // delete operation - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.UpdateUserAuthorizationGroupMembership"), mock.MatchedBy(func(in map[string]interface{}) bool { - groupNames, groupNamesOk := in["groupNames"].([]string) - return in["memberUserId"] == memberId && groupNamesOk && len(groupNames) == 0 - })).Return(nil) - - // update - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.UpdateUserAuthorizationGroupMembership"), mock.MatchedBy(func(in map[string]interface{}) bool { - groupNames, groupNamesOk := in["groupNames"].([]string) - return in["memberUserId"] == memberId && groupNamesOk && slices.Contains(groupNames, groupNameUpdated) - })).Return(nil).Run(func(args mock.Arguments) { - mcClient.ExpectedCalls = slices.DeleteFunc(mcClient.ExpectedCalls, func(call *mock.Call) bool { return call.Arguments.Is(readUser.Arguments...) }) - readUser = mcClient.On("Query", mock.Anything, mock.AnythingOfType("*client.GetUsersInAccount"), mock.MatchedBy(func(in map[string]interface{}) bool { - return in["email"] == memberEmail && in["after"] == (*string)(nil) - })).Return(nil).Run(func(args mock.Arguments) { - getResult := args.Get(1).(*client.GetUsersInAccount) - node := client.User{CognitoUserId: memberId, IsSso: false, Email: memberEmail} - node.Auth.Groups = []string{groupNameUpdated} - getResult.GetUsersInAccount.Edges = []struct{ Node client.User }{{Node: node}} - }) - }) - return &mcClient -} diff --git a/monte_carlo/resources/transactional_warehouse_test.go b/monte_carlo/resources/transactional_warehouse_test.go deleted file mode 100644 index 88c0929..0000000 --- a/monte_carlo/resources/transactional_warehouse_test.go +++ /dev/null @@ -1,174 +0,0 @@ -package resources_test - -import ( - "fmt" - "testing" - - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client" - cmock "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/client/mock" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/common" - "github.com/kiwicom/terraform-provider-montecarlo/monte_carlo/provider" - - "github.com/hashicorp/terraform-plugin-framework/providerserver" - "github.com/hashicorp/terraform-plugin-go/tfprotov6" - "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/stretchr/testify/mock" -) - -func TestAccTransactionalWarehouseResource(t *testing.T) { - name1 := "name1" - name2 := "name2" - uuid := "8bfc4" - connectionUuid := "8cd5a" - dcId := "dataCollector1" - username1 := "user1" - password1 := "password1" - username2 := "user2" - password2 := "password2" - - providerContext := &common.ProviderContext{MonteCarloClient: initTransactionalWarehouseMonteCarloClient( - uuid, connectionUuid, dcId, name1, name2, username1, username2, password1, password2, - )} - providerFactories := map[string]func() (tfprotov6.ProviderServer, error){ - "montecarlo": providerserver.NewProtocol6WithError(provider.New("test", providerContext)()), - } - - resource.Test(t, resource.TestCase{ - PreCheck: func() {}, - ProtoV6ProviderFactories: providerFactories, - Steps: []resource.TestStep{ - { // Create and Read testing - Config: transactionalWarehouseConfig(name1, dcId, username1, password1), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "uuid", uuid), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "connection_uuid", connectionUuid), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "name", name1), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "collector_uuid", dcId), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "deletion_protection", "false"), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.host", "host"), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.port", "5432"), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.database", "database"), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.username", username1), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.password", password1), - ), - }, - { // ImportState testing - ResourceName: "montecarlo_transactional_warehouse.test", - ImportState: true, - ImportStateVerify: true, - ImportStateId: fmt.Sprintf("%s,%s,%s", uuid, connectionUuid, dcId), - ImportStateVerifyIdentifierAttribute: "uuid", - ImportStateVerifyIgnore: []string{"db_type", "deletion_protection", "configuration"}, - }, - { // Update and Read testing - Config: transactionalWarehouseConfig(name2, dcId, username2, password2), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "uuid", uuid), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "connection_uuid", connectionUuid), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "name", name2), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "collector_uuid", dcId), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "deletion_protection", "false"), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.host", "host"), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.port", "5432"), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.database", "database"), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.username", username2), - resource.TestCheckResourceAttr("montecarlo_transactional_warehouse.test", "configuration.password", password2), - ), - }, - }, - }) -} - -func transactionalWarehouseConfig(name string, dcid string, username string, password string) string { - return fmt.Sprintf(` -provider "montecarlo" { - account_service_key = { - id = "montecarlo" - token = "montecarlo" - } -} - -resource "montecarlo_transactional_warehouse" "test" { - name = %[1]q - collector_uuid = %[2]q - db_type = "POSTGRES" # POSTGRES | MYSQL | SQL-SERVER - deletion_protection = false - - configuration = { - host = "host" - port = 5432 - database = "database" - username = %[3]q #(secret) - password = %[4]q #(secret) - } -} -`, name, dcid, username, password) -} - -func initTransactionalWarehouseMonteCarloClient(uuid, connectionUuid, dcId, name1, name2, username1, username2, password1, password2 string) client.MonteCarloClient { - mcClient := cmock.MonteCarloClient{} - testKey := "testKey" - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.TestDatabaseCredentials"), mock.MatchedBy(func(in map[string]interface{}) bool { - return in["connectionType"] == client.TransactionalConnectionType && - in["dbType"] == "postgres" && - in["host"] == "host" && - in["port"] == int64(5432) && - in["dbName"] == "database" && - in["user"] == username1 && - in["password"] == password1 - })).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.TestDatabaseCredentials) - arg.TestDatabaseCredentials.Key = testKey - arg.TestDatabaseCredentials.Success = true - arg.TestDatabaseCredentials.Validations = []client.DatabaseTestDiagnostic{} - arg.TestDatabaseCredentials.Warnings = []client.DatabaseTestDiagnostic{} - }) - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.AddConnection"), mock.MatchedBy(func(in map[string]interface{}) bool { - return in["connectionType"] == client.TransactionalConnectionType && - (in["createWarehouseType"] != nil && *in["createWarehouseType"].(*string) == client.TransactionalConnectionType) && - (in["dcId"] != nil && *in["dcId"].(*client.UUID) == client.UUID(dcId)) && - (in["name"] != nil && *in["name"].(*string) == name1) && - in["dwId"] == (*client.UUID)(nil) && in["key"] == testKey - })).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.AddConnection) - arg.AddConnection.Connection.Uuid = connectionUuid - arg.AddConnection.Connection.Warehouse.Uuid = uuid - arg.AddConnection.Connection.Warehouse.Name = name1 - }) - - // Read operations - readVariables1 := map[string]interface{}{"uuid": client.UUID(uuid)} - readResponse1 := []byte(fmt.Sprintf(`{"getWarehouse":{"name":%[1]q,"connections":[{"uuid":%[2]q,`+ - `"type":%[3]q}],"dataCollector":{"uuid":%[4]q}}}`, name1, connectionUuid, client.TransactionalConnectionTypeResponse, dcId)) - mcClient.On("ExecRaw", mock.Anything, client.GetWarehouseQuery, readVariables1).Return(readResponse1, nil) - - // Delete operations - deleteVariables1 := map[string]interface{}{"connectionId": client.UUID(connectionUuid)} - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.RemoveConnection"), deleteVariables1).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.RemoveConnection) - arg.RemoveConnection.Success = true - }) - - // Update operations - updateVariables := map[string]interface{}{"dwId": client.UUID(uuid), "name": name2} - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.SetWarehouseName"), updateVariables).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.SetWarehouseName) - arg.SetWarehouseName.Warehouse.Uuid = uuid - arg.SetWarehouseName.Warehouse.Name = name2 - }) - mcClient.On("Mutate", mock.Anything, mock.AnythingOfType("*client.UpdateCredentials"), mock.MatchedBy(func(in map[string]interface{}) bool { - return in["connectionId"] == client.UUID(connectionUuid) && - in["changes"] == client.JSONString(fmt.Sprintf( - `{"db_type":%[1]q, "host": %[2]q, "port": %[3]d, "user": %[4]q, "password": %[5]q}`, - "postgres", "host", int64(5432), username2, password2)) - })).Return(nil).Run(func(args mock.Arguments) { - arg := args.Get(1).(*client.UpdateCredentials) - arg.UpdateCredentials.Success = true - // after update, read operation must return new results - mcClient.On("ExecRaw", mock.Anything, client.GetWarehouseQuery, readVariables1).Unset() - readResponse := []byte(fmt.Sprintf(`{"getWarehouse":{"name":%[1]q,"connections":[{"uuid":%[2]q,`+ - `"type":%[3]q}],"dataCollector":{"uuid":%[4]q}}}`, name2, connectionUuid, client.TransactionalConnectionTypeResponse, dcId)) - mcClient.On("ExecRaw", mock.Anything, client.GetWarehouseQuery, readVariables1).Return(readResponse, nil) - }) - return &mcClient -}