terraform-provider-stackitp.../stackit/internal/services/postgresflexalpha/instance/resource_test.go
Marcel S. Henselin 32e41d8b44
feat: testing (#34)
## Description

<!-- **Please link some issue here describing what you are trying to achieve.**

In case there is no issue present for your PR, please consider creating one.
At least please give us some description what you are trying to achieve and why your change is needed. -->

relates to #1234

## Checklist

- [ ] Issue was linked above
- [ ] Code format was applied: `make fmt`
- [ ] Examples were added / adjusted (see `examples/` directory)
- [x] Docs are up-to-date: `make generate-docs` (will be checked by CI)
- [ ] Unit tests got implemented or updated
- [ ] Acceptance tests got implemented or updated (see e.g. [here](f5f99d1709/stackit/internal/services/dns/dns_acc_test.go))
- [x] Unit tests are passing: `make test` (will be checked by CI)
- [x] No linter issues: `make lint` (will be checked by CI)

Reviewed-on: #34
Co-authored-by: Marcel S. Henselin <marcel.henselin@stackit.cloud>
Co-committed-by: Marcel S. Henselin <marcel.henselin@stackit.cloud>
2026-02-06 09:57:51 +00:00

280 lines
7 KiB
Go

package postgresflexalpha
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/testutil"
)
var (
validFlavor = "2.4"
kekKeyRingId = ""
kekKeyVersion = ""
kekKeySA = ""
)
func testAccPreCheck(t *testing.T) {
// TODO: if needed ...
}
//func TestAccResourceExample_parallel(t *testing.T) {
// t.Parallel()
//
// exData := resData{
// Region: "eu01",
// ServiceAccountFilePath: sa_file,
// ProjectID: project_id,
// Name: acctest.RandomWithPrefix("tf-acc"),
// }
//
// resource.Test(t, resource.TestCase{
// ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
// Steps: []resource.TestStep{
// {
// Config: testAccResourceEncryptionExampleConfig(exData),
// Check: resource.TestCheckResourceAttrSet("example_resource.test", "id"),
// },
// },
// })
//}
type resData struct {
ServiceAccountFilePath string
ProjectID string
Region string
Name string
Flavor string
BackupSchedule string
RetentionDays uint32
}
func getExample() resData {
return resData{
Region: testutil.Region,
ServiceAccountFilePath: testutil.ServiceAccountFile,
ProjectID: testutil.ProjectId,
Name: acctest.RandomWithPrefix("tf-acc"),
Flavor: "2.4",
BackupSchedule: "0 0 * * *",
RetentionDays: 33,
}
}
func TestAccResourceExample_basic(t *testing.T) {
exData := getExample()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
Config: testAccResourceNoEncryptionExampleConfig(exData),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("example_resource.test", "name", exData.Name),
resource.TestCheckResourceAttrSet("example_resource.test", "id"),
),
},
//// Create and verify
//{
// Config: testAccResourceNoEncryptionExampleConfig(exData),
// Check: resource.ComposeTestCheckFunc(
// resource.TestCheckResourceAttr("example_resource.test", "name", exData.Name),
// ),
//},
//// Update and verify
//{
// Config: testAccResourceNoEncryptionExampleConfig(exData),
// Check: resource.ComposeTestCheckFunc(
// resource.TestCheckResourceAttr("example_resource.test", "name", exData.Name),
// ),
//},
// Import test
{
ResourceName: "example_resource.test",
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func testAccResourceNoEncryptionExampleConfig(data resData) string {
return fmt.Sprintf(`
%[1]s
resource "stackitprivatepreview_postgresflexalpha_instance" "test" {
project_id = %[2]q
name = %[3]q
backup_schedule = %[4]q
retention_days = %[5]d
flavor_id = %[6]q
replicas = 1
storage = {
performance_class = "premium-perf2-stackit"
size = 10
}
network = {
acl = ["0.0.0.0/0"]
access_scope = "PUBLIC"
}
version = 17
}
`,
testutil.PostgresFlexProviderConfig(data.ServiceAccountFilePath),
data.ProjectID,
data.Name,
data.BackupSchedule,
data.RetentionDays,
data.Flavor,
data.Name,
)
}
func testAccResourceEncryptionExampleConfig(data resData) string {
return fmt.Sprintf(`
%[1]s
resource "stackitprivatepreview_postgresflexalpha_instance" "test" {
project_id = %[2]q
name = %[3]q
backup_schedule = "0 0 * * *"
retention_days = 45
flavor_id = "2.1"
replicas = 1
storage = {
performance_class = "premium-perf2-stackit"
size = 10
}
encryption = {
kek_key_id = "key01"
kek_key_ring_id = "key_ring_01"
kek_key_version = 1
service_account = "service@account.email"
}
network = {
acl = ["0.0.0.0/0"]
access_scope = "PUBLIC"
}
version = 14
}
`,
testutil.PostgresFlexProviderConfig(data.ServiceAccountFilePath),
data.ProjectID,
data.Name,
)
}
func testCheckResourceExists(resourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("resource not found: %s", resourceName)
}
if rs.Primary.ID == "" {
return fmt.Errorf("resource ID not set")
}
// Verify resource exists in the API
//client := testAccProvider.Meta().(*APIClient)
//_, err := client.GetResource(rs.Primary.ID)
//if err != nil {
// return fmt.Errorf("error fetching resource: %w", err)
//}
return nil
}
}
func setupMockServer() *httptest.Server {
mux := http.NewServeMux()
mux.HandleFunc("/api/resources", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]string{
"id": "mock-id-123",
"name": "test-resource",
})
case http.MethodGet:
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode([]map[string]string{})
}
})
return httptest.NewServer(mux)
}
func TestUnitResourceCreate(t *testing.T) {
server := setupMockServer()
defer server.Close()
// Configure provider to use mock server URL
os.Setenv("API_ENDPOINT", server.URL)
// Run unit tests against mock
}
// type postgresFlexClientMocked struct {
// returnError bool
// getFlavorsResp *postgresflex.GetFlavorsResponse
// }
//
// func (c *postgresFlexClientMocked) ListFlavorsExecute(_ context.Context, _, _ string) (*postgresflex.GetFlavorsResponse, error) {
// if c.returnError {
// return nil, fmt.Errorf("get flavors failed")
// }
//
// return c.getFlavorsResp, nil
// }
//func TestNewInstanceResource(t *testing.T) {
// exData := resData{
// Region: "eu01",
// ServiceAccountFilePath: sa_file,
// ProjectID: project_id,
// Name: "testRes",
// }
// resource.Test(t, resource.TestCase{
// ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
// Steps: []resource.TestStep{
// {
// Config: testAccResourceEncryptionExampleConfig(exData),
// Check: resource.ComposeAggregateTestCheckFunc(
// resource.TestCheckResourceAttr("example_resource.test", "name", exData.Name),
// resource.TestCheckResourceAttrSet("example_resource.test", "id"),
// ),
// },
// },
// })
//
// //tests := []struct {
// // name string
// // want resource.Resource
// //}{
// // {
// // name: "create empty instance resource",
// // want: &instanceResource{},
// // },
// //}
// //for _, tt := range tests {
// // t.Run(tt.name, func(t *testing.T) {
// // if got := NewInstanceResource(); !reflect.DeepEqual(got, tt.want) {
// // t.Errorf("NewInstanceResource() = %v, want %v", got, tt.want)
// // }
// // })
// //}
//}