feat(mongodbflex): region adjustment (#914)

relates to STACKITTPR-282
This commit is contained in:
Ruben Hönle 2025-07-21 14:37:47 +02:00 committed by GitHub
parent 6555a99a6d
commit 189fa1ece7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 388 additions and 175 deletions

View file

@ -36,6 +36,7 @@ type DataSourceModel struct {
Roles types.Set `tfsdk:"roles"`
Host types.String `tfsdk:"host"`
Port types.Int64 `tfsdk:"port"`
Region types.String `tfsdk:"region"`
}
// NewUserDataSource is a helper function to simplify the provider implementation.
@ -45,37 +46,40 @@ func NewUserDataSource() datasource.DataSource {
// userDataSource is the data source implementation.
type userDataSource struct {
client *mongodbflex.APIClient
client *mongodbflex.APIClient
providerData core.ProviderData
}
// Metadata returns the data source type name.
func (r *userDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
func (d *userDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_mongodbflex_user"
}
// Configure adds the provider configured client to the data source.
func (r *userDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
func (d *userDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
var ok bool
d.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
apiClient := mongodbflexUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics)
apiClient := mongodbflexUtils.ConfigureClient(ctx, &d.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
r.client = apiClient
d.client = apiClient
tflog.Info(ctx, "MongoDB Flex user client configured")
}
// Schema defines the schema for the data source.
func (r *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
func (d *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
descriptions := map[string]string{
"main": "MongoDB Flex user data source schema. Must have a `region` specified in the provider configuration.",
"id": "Terraform's internal data source. ID. It is structured as \"`project_id`,`instance_id`,`user_id`\".",
"id": "Terraform's internal data source. ID. It is structured as \"`project_id`,`region`,`instance_id`,`user_id`\".",
"user_id": "User ID.",
"instance_id": "ID of the MongoDB Flex instance.",
"project_id": "STACKIT project ID to which the instance is associated.",
"region": "The resource region. If not defined, the provider region is used.",
}
resp.Schema = schema.Schema{
@ -124,12 +128,18 @@ func (r *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, r
"port": schema.Int64Attribute{
Computed: true,
},
"region": schema.StringAttribute{
Optional: true,
// must be computed to allow for storing the override value from the provider
Computed: true,
Description: descriptions["region"],
},
},
}
}
// Read refreshes the Terraform state with the latest data.
func (r *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
func (d *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model DataSourceModel
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
@ -137,13 +147,15 @@ func (r *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, r
return
}
projectId := model.ProjectId.ValueString()
region := d.providerData.GetRegionWithOverride(model.Region)
instanceId := model.InstanceId.ValueString()
userId := model.UserId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
ctx = tflog.SetField(ctx, "user_id", userId)
recordSetResp, err := r.client.GetUser(ctx, projectId, instanceId, userId).Execute()
recordSetResp, err := d.client.GetUser(ctx, projectId, instanceId, userId, region).Execute()
if err != nil {
utils.LogError(
ctx,
@ -160,7 +172,7 @@ func (r *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, r
}
// Map response body to schema and populate Computed attribute values
err = mapDataSourceFields(recordSetResp, &model)
err = mapDataSourceFields(recordSetResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", fmt.Sprintf("Processing API payload: %v", err))
return
@ -175,7 +187,7 @@ func (r *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, r
tflog.Info(ctx, "MongoDB Flex user read")
}
func mapDataSourceFields(userResp *mongodbflex.GetUserResponse, model *DataSourceModel) error {
func mapDataSourceFields(userResp *mongodbflex.GetUserResponse, model *DataSourceModel, region string) error {
if userResp == nil || userResp.Item == nil {
return fmt.Errorf("response is nil")
}
@ -192,7 +204,7 @@ func mapDataSourceFields(userResp *mongodbflex.GetUserResponse, model *DataSourc
} else {
return fmt.Errorf("user id not present")
}
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), model.InstanceId.ValueString(), userId)
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, model.InstanceId.ValueString(), userId)
model.UserId = types.StringValue(userId)
model.Username = types.StringPointerValue(user.Username)
model.Database = types.StringPointerValue(user.Database)

View file

@ -1,6 +1,7 @@
package mongodbflex
import (
"fmt"
"testing"
"github.com/google/go-cmp/cmp"
@ -14,6 +15,7 @@ func TestMapDataSourceFields(t *testing.T) {
tests := []struct {
description string
input *mongodbflex.GetUserResponse
region string
expected DataSourceModel
isValid bool
}{
@ -22,11 +24,12 @@ func TestMapDataSourceFields(t *testing.T) {
&mongodbflex.GetUserResponse{
Item: &mongodbflex.InstanceResponseUser{},
},
testRegion,
DataSourceModel{
Id: types.StringValue("pid,iid,uid"),
UserId: types.StringValue("uid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s", projectId, testRegion, instanceId, userId)),
UserId: types.StringValue(userId),
InstanceId: types.StringValue(instanceId),
ProjectId: types.StringValue(projectId),
Username: types.StringNull(),
Database: types.StringNull(),
Roles: types.SetNull(types.StringType),
@ -50,11 +53,12 @@ func TestMapDataSourceFields(t *testing.T) {
Port: utils.Ptr(int64(1234)),
},
},
testRegion,
DataSourceModel{
Id: types.StringValue("pid,iid,uid"),
UserId: types.StringValue("uid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s", projectId, testRegion, instanceId, userId)),
UserId: types.StringValue(userId),
InstanceId: types.StringValue(instanceId),
ProjectId: types.StringValue(projectId),
Username: types.StringValue("username"),
Database: types.StringValue("database"),
Roles: types.SetValueMust(types.StringType, []attr.Value{
@ -71,7 +75,7 @@ func TestMapDataSourceFields(t *testing.T) {
"null_fields_and_int_conversions",
&mongodbflex.GetUserResponse{
Item: &mongodbflex.InstanceResponseUser{
Id: utils.Ptr("uid"),
Id: utils.Ptr(userId),
Roles: &[]string{},
Username: nil,
Database: nil,
@ -79,11 +83,12 @@ func TestMapDataSourceFields(t *testing.T) {
Port: utils.Ptr(int64(2123456789)),
},
},
testRegion,
DataSourceModel{
Id: types.StringValue("pid,iid,uid"),
UserId: types.StringValue("uid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s", projectId, testRegion, instanceId, userId)),
UserId: types.StringValue(userId),
InstanceId: types.StringValue(instanceId),
ProjectId: types.StringValue(projectId),
Username: types.StringNull(),
Database: types.StringNull(),
Roles: types.SetValueMust(types.StringType, []attr.Value{}),
@ -95,12 +100,14 @@ func TestMapDataSourceFields(t *testing.T) {
{
"nil_response",
nil,
testRegion,
DataSourceModel{},
false,
},
{
"nil_response_2",
&mongodbflex.GetUserResponse{},
testRegion,
DataSourceModel{},
false,
},
@ -109,6 +116,7 @@ func TestMapDataSourceFields(t *testing.T) {
&mongodbflex.GetUserResponse{
Item: &mongodbflex.InstanceResponseUser{},
},
testRegion,
DataSourceModel{},
false,
},
@ -120,7 +128,7 @@ func TestMapDataSourceFields(t *testing.T) {
InstanceId: tt.expected.InstanceId,
UserId: tt.expected.UserId,
}
err := mapDataSourceFields(tt.input, state)
err := mapDataSourceFields(tt.input, state, tt.region)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}

View file

@ -32,6 +32,7 @@ var (
_ resource.Resource = &userResource{}
_ resource.ResourceWithConfigure = &userResource{}
_ resource.ResourceWithImportState = &userResource{}
_ resource.ResourceWithModifyPlan = &userResource{}
)
type Model struct {
@ -46,6 +47,7 @@ type Model struct {
Host types.String `tfsdk:"host"`
Port types.Int64 `tfsdk:"port"`
Uri types.String `tfsdk:"uri"`
Region types.String `tfsdk:"region"`
}
// NewUserResource is a helper function to simplify the provider implementation.
@ -55,7 +57,8 @@ func NewUserResource() resource.Resource {
// userResource is the resource implementation.
type userResource struct {
client *mongodbflex.APIClient
client *mongodbflex.APIClient
providerData core.ProviderData
}
// Metadata returns the resource type name.
@ -65,12 +68,13 @@ func (r *userResource) Metadata(_ context.Context, req resource.MetadataRequest,
// Configure adds the provider configured client to the resource.
func (r *userResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
var ok bool
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
apiClient := mongodbflexUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics)
apiClient := mongodbflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
@ -78,6 +82,36 @@ func (r *userResource) Configure(ctx context.Context, req resource.ConfigureRequ
tflog.Info(ctx, "MongoDB Flex user client configured")
}
// ModifyPlan implements resource.ResourceWithModifyPlan.
// Use the modifier to set the effective region in the current plan.
func (r *userResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform
var configModel Model
// skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() {
return
}
resp.Diagnostics.Append(req.Config.Get(ctx, &configModel)...)
if resp.Diagnostics.HasError() {
return
}
var planModel Model
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
if resp.Diagnostics.HasError() {
return
}
utils.AdaptRegion(ctx, configModel.Region, &planModel.Region, r.providerData.GetRegion(), resp)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...)
if resp.Diagnostics.HasError() {
return
}
}
// Schema defines the schema for the resource.
func (r *userResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
descriptions := map[string]string{
@ -87,6 +121,7 @@ func (r *userResource) Schema(_ context.Context, _ resource.SchemaRequest, resp
"instance_id": "ID of the MongoDB Flex instance.",
"project_id": "STACKIT project ID to which the instance is associated.",
"roles": "Database access levels for the user. Some of the possible values are: [`read`, `readWrite`, `readWriteAnyDatabase`]",
"region": "The resource region. If not defined, the provider region is used.",
}
resp.Schema = schema.Schema{
@ -166,6 +201,15 @@ func (r *userResource) Schema(_ context.Context, _ resource.SchemaRequest, resp
Computed: true,
Sensitive: true,
},
"region": schema.StringAttribute{
Optional: true,
// must be computed to allow for storing the override value from the provider
Computed: true,
Description: descriptions["region"],
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
},
}
}
@ -179,8 +223,10 @@ func (r *userResource) Create(ctx context.Context, req resource.CreateRequest, r
return
}
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
instanceId := model.InstanceId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
var roles []string
@ -199,7 +245,7 @@ func (r *userResource) Create(ctx context.Context, req resource.CreateRequest, r
return
}
// Create new user
userResp, err := r.client.CreateUser(ctx, projectId, instanceId).CreateUserPayload(*payload).Execute()
userResp, err := r.client.CreateUser(ctx, projectId, instanceId, region).CreateUserPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Calling API: %v", err))
return
@ -212,7 +258,7 @@ func (r *userResource) Create(ctx context.Context, req resource.CreateRequest, r
ctx = tflog.SetField(ctx, "user_id", userId)
// Map response body to schema
err = mapFieldsCreate(userResp, &model)
err = mapFieldsCreate(userResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Processing API payload: %v", err))
return
@ -235,13 +281,15 @@ func (r *userResource) Read(ctx context.Context, req resource.ReadRequest, resp
return
}
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
instanceId := model.InstanceId.ValueString()
userId := model.UserId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
ctx = tflog.SetField(ctx, "user_id", userId)
recordSetResp, err := r.client.GetUser(ctx, projectId, instanceId, userId).Execute()
recordSetResp, err := r.client.GetUser(ctx, projectId, instanceId, userId, region).Execute()
if err != nil {
oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
if ok && oapiErr.StatusCode == http.StatusNotFound {
@ -253,7 +301,7 @@ func (r *userResource) Read(ctx context.Context, req resource.ReadRequest, resp
}
// Map response body to schema
err = mapFields(recordSetResp, &model)
err = mapFields(recordSetResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", fmt.Sprintf("Processing API payload: %v", err))
return
@ -278,9 +326,11 @@ func (r *userResource) Update(ctx context.Context, req resource.UpdateRequest, r
return
}
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
instanceId := model.InstanceId.ValueString()
userId := model.UserId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
ctx = tflog.SetField(ctx, "user_id", userId)
@ -309,20 +359,20 @@ func (r *userResource) Update(ctx context.Context, req resource.UpdateRequest, r
}
// Update existing instance
err = r.client.UpdateUser(ctx, projectId, instanceId, userId).UpdateUserPayload(*payload).Execute()
err = r.client.UpdateUser(ctx, projectId, instanceId, userId, region).UpdateUserPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating user", err.Error())
return
}
userResp, err := r.client.GetUser(ctx, projectId, instanceId, userId).Execute()
userResp, err := r.client.GetUser(ctx, projectId, instanceId, userId, region).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating user", fmt.Sprintf("Calling API: %v", err))
return
}
// Map response body to schema
err = mapFields(userResp, &stateModel)
err = mapFields(userResp, &stateModel, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating user", fmt.Sprintf("Processing API payload: %v", err))
return
@ -348,14 +398,16 @@ func (r *userResource) Delete(ctx context.Context, req resource.DeleteRequest, r
}
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
instanceId := model.InstanceId.ValueString()
userId := model.UserId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
ctx = tflog.SetField(ctx, "user_id", userId)
// Delete user
err := r.client.DeleteUser(ctx, projectId, instanceId, userId).Execute()
err := r.client.DeleteUser(ctx, projectId, instanceId, userId, region).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting user", fmt.Sprintf("Calling API: %v", err))
return
@ -367,17 +419,18 @@ func (r *userResource) Delete(ctx context.Context, req resource.DeleteRequest, r
// The expected format of the resource import identifier is: project_id,zone_id,record_set_id
func (r *userResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics,
"Error importing user",
fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[user_id], got %q", req.ID),
fmt.Sprintf("Expected import identifier with format [project_id],[region],[instance_id],[user_id], got %q", req.ID),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), idParts[2])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), idParts[3])...)
core.LogAndAddWarning(ctx, &resp.Diagnostics,
"MongoDB Flex user imported with empty password and empty uri",
"The user password and uri are not imported as they are only available upon creation of a new user. The password and uri fields will be empty.",
@ -385,7 +438,7 @@ func (r *userResource) ImportState(ctx context.Context, req resource.ImportState
tflog.Info(ctx, "MongoDB Flex user state imported")
}
func mapFieldsCreate(userResp *mongodbflex.CreateUserResponse, model *Model) error {
func mapFieldsCreate(userResp *mongodbflex.CreateUserResponse, model *Model, region string) error {
if userResp == nil || userResp.Item == nil {
return fmt.Errorf("response is nil")
}
@ -398,7 +451,8 @@ func mapFieldsCreate(userResp *mongodbflex.CreateUserResponse, model *Model) err
return fmt.Errorf("user id not present")
}
userId := *user.Id
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), model.InstanceId.ValueString(), userId)
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, model.InstanceId.ValueString(), userId)
model.Region = types.StringValue(region)
model.UserId = types.StringValue(userId)
model.Username = types.StringPointerValue(user.Username)
model.Database = types.StringPointerValue(user.Database)
@ -427,7 +481,7 @@ func mapFieldsCreate(userResp *mongodbflex.CreateUserResponse, model *Model) err
return nil
}
func mapFields(userResp *mongodbflex.GetUserResponse, model *Model) error {
func mapFields(userResp *mongodbflex.GetUserResponse, model *Model, region string) error {
if userResp == nil || userResp.Item == nil {
return fmt.Errorf("response is nil")
}
@ -444,7 +498,8 @@ func mapFields(userResp *mongodbflex.GetUserResponse, model *Model) error {
} else {
return fmt.Errorf("user id not present")
}
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), model.InstanceId.ValueString(), userId)
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, model.InstanceId.ValueString(), userId)
model.Region = types.StringValue(region)
model.UserId = types.StringValue(userId)
model.Username = types.StringPointerValue(user.Username)
model.Database = types.StringPointerValue(user.Database)

View file

@ -1,8 +1,11 @@
package mongodbflex
import (
"fmt"
"testing"
"github.com/google/uuid"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
@ -10,10 +13,21 @@ import (
"github.com/stackitcloud/stackit-sdk-go/services/mongodbflex"
)
const (
testRegion = "eu02"
)
var (
projectId = uuid.NewString()
instanceId = uuid.NewString()
userId = uuid.NewString()
)
func TestMapFieldsCreate(t *testing.T) {
tests := []struct {
description string
input *mongodbflex.CreateUserResponse
region string
expected Model
isValid bool
}{
@ -21,15 +35,16 @@ func TestMapFieldsCreate(t *testing.T) {
"default_values",
&mongodbflex.CreateUserResponse{
Item: &mongodbflex.User{
Id: utils.Ptr("uid"),
Id: utils.Ptr(userId),
Password: utils.Ptr(""),
},
},
testRegion,
Model{
Id: types.StringValue("pid,iid,uid"),
UserId: types.StringValue("uid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s", projectId, testRegion, instanceId, userId)),
UserId: types.StringValue(userId),
InstanceId: types.StringValue(instanceId),
ProjectId: types.StringValue(projectId),
Username: types.StringNull(),
Database: types.StringNull(),
Roles: types.SetNull(types.StringType),
@ -37,6 +52,7 @@ func TestMapFieldsCreate(t *testing.T) {
Host: types.StringNull(),
Port: types.Int64Null(),
Uri: types.StringNull(),
Region: types.StringValue(testRegion),
},
true,
},
@ -44,7 +60,7 @@ func TestMapFieldsCreate(t *testing.T) {
"simple_values",
&mongodbflex.CreateUserResponse{
Item: &mongodbflex.User{
Id: utils.Ptr("uid"),
Id: utils.Ptr(userId),
Roles: &[]string{
"role_1",
"role_2",
@ -58,11 +74,12 @@ func TestMapFieldsCreate(t *testing.T) {
Uri: utils.Ptr("uri"),
},
},
testRegion,
Model{
Id: types.StringValue("pid,iid,uid"),
UserId: types.StringValue("uid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s", projectId, testRegion, instanceId, userId)),
UserId: types.StringValue(userId),
InstanceId: types.StringValue(instanceId),
ProjectId: types.StringValue(projectId),
Username: types.StringValue("username"),
Database: types.StringValue("database"),
Roles: types.SetValueMust(types.StringType, []attr.Value{
@ -74,6 +91,7 @@ func TestMapFieldsCreate(t *testing.T) {
Host: types.StringValue("host"),
Port: types.Int64Value(1234),
Uri: types.StringValue("uri"),
Region: types.StringValue(testRegion),
},
true,
},
@ -81,7 +99,7 @@ func TestMapFieldsCreate(t *testing.T) {
"null_fields_and_int_conversions",
&mongodbflex.CreateUserResponse{
Item: &mongodbflex.User{
Id: utils.Ptr("uid"),
Id: utils.Ptr(userId),
Roles: &[]string{},
Username: nil,
Database: nil,
@ -91,11 +109,12 @@ func TestMapFieldsCreate(t *testing.T) {
Uri: nil,
},
},
testRegion,
Model{
Id: types.StringValue("pid,iid,uid"),
UserId: types.StringValue("uid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s", projectId, testRegion, instanceId, userId)),
UserId: types.StringValue(userId),
InstanceId: types.StringValue(instanceId),
ProjectId: types.StringValue(projectId),
Username: types.StringNull(),
Database: types.StringNull(),
Roles: types.SetValueMust(types.StringType, []attr.Value{}),
@ -103,18 +122,21 @@ func TestMapFieldsCreate(t *testing.T) {
Host: types.StringNull(),
Port: types.Int64Value(2123456789),
Uri: types.StringNull(),
Region: types.StringValue(testRegion),
},
true,
},
{
"nil_response",
nil,
testRegion,
Model{},
false,
},
{
"nil_response_2",
&mongodbflex.CreateUserResponse{},
testRegion,
Model{},
false,
},
@ -123,6 +145,7 @@ func TestMapFieldsCreate(t *testing.T) {
&mongodbflex.CreateUserResponse{
Item: &mongodbflex.User{},
},
testRegion,
Model{},
false,
},
@ -130,9 +153,10 @@ func TestMapFieldsCreate(t *testing.T) {
"no_password",
&mongodbflex.CreateUserResponse{
Item: &mongodbflex.User{
Id: utils.Ptr("uid"),
Id: utils.Ptr(userId),
},
},
testRegion,
Model{},
false,
},
@ -143,7 +167,7 @@ func TestMapFieldsCreate(t *testing.T) {
ProjectId: tt.expected.ProjectId,
InstanceId: tt.expected.InstanceId,
}
err := mapFieldsCreate(tt.input, state)
err := mapFieldsCreate(tt.input, state, tt.region)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
@ -164,6 +188,7 @@ func TestMapFields(t *testing.T) {
tests := []struct {
description string
input *mongodbflex.GetUserResponse
region string
expected Model
isValid bool
}{
@ -172,16 +197,18 @@ func TestMapFields(t *testing.T) {
&mongodbflex.GetUserResponse{
Item: &mongodbflex.InstanceResponseUser{},
},
testRegion,
Model{
Id: types.StringValue("pid,iid,uid"),
UserId: types.StringValue("uid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s", projectId, testRegion, instanceId, userId)),
UserId: types.StringValue(userId),
InstanceId: types.StringValue(instanceId),
ProjectId: types.StringValue(projectId),
Username: types.StringNull(),
Database: types.StringNull(),
Roles: types.SetNull(types.StringType),
Host: types.StringNull(),
Port: types.Int64Null(),
Region: types.StringValue(testRegion),
},
true,
},
@ -200,11 +227,12 @@ func TestMapFields(t *testing.T) {
Port: utils.Ptr(int64(1234)),
},
},
testRegion,
Model{
Id: types.StringValue("pid,iid,uid"),
UserId: types.StringValue("uid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s", projectId, testRegion, instanceId, userId)),
UserId: types.StringValue(userId),
InstanceId: types.StringValue(instanceId),
ProjectId: types.StringValue(projectId),
Username: types.StringValue("username"),
Database: types.StringValue("database"),
Roles: types.SetValueMust(types.StringType, []attr.Value{
@ -212,8 +240,9 @@ func TestMapFields(t *testing.T) {
types.StringValue("role_2"),
types.StringValue(""),
}),
Host: types.StringValue("host"),
Port: types.Int64Value(1234),
Host: types.StringValue("host"),
Port: types.Int64Value(1234),
Region: types.StringValue(testRegion),
},
true,
},
@ -221,7 +250,7 @@ func TestMapFields(t *testing.T) {
"null_fields_and_int_conversions",
&mongodbflex.GetUserResponse{
Item: &mongodbflex.InstanceResponseUser{
Id: utils.Ptr("uid"),
Id: utils.Ptr(userId),
Roles: &[]string{},
Username: nil,
Database: nil,
@ -229,28 +258,32 @@ func TestMapFields(t *testing.T) {
Port: utils.Ptr(int64(2123456789)),
},
},
testRegion,
Model{
Id: types.StringValue("pid,iid,uid"),
UserId: types.StringValue("uid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s", projectId, testRegion, instanceId, userId)),
UserId: types.StringValue(userId),
InstanceId: types.StringValue(instanceId),
ProjectId: types.StringValue(projectId),
Username: types.StringNull(),
Database: types.StringNull(),
Roles: types.SetValueMust(types.StringType, []attr.Value{}),
Host: types.StringNull(),
Port: types.Int64Value(2123456789),
Region: types.StringValue(testRegion),
},
true,
},
{
"nil_response",
nil,
testRegion,
Model{},
false,
},
{
"nil_response_2",
&mongodbflex.GetUserResponse{},
testRegion,
Model{},
false,
},
@ -259,6 +292,7 @@ func TestMapFields(t *testing.T) {
&mongodbflex.GetUserResponse{
Item: &mongodbflex.InstanceResponseUser{},
},
testRegion,
Model{},
false,
},
@ -270,7 +304,7 @@ func TestMapFields(t *testing.T) {
InstanceId: tt.expected.InstanceId,
UserId: tt.expected.UserId,
}
err := mapFields(tt.input, state)
err := mapFields(tt.input, state, tt.region)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}