From 73fdc43ea3b84389c1c17fe761fafd654def42e5 Mon Sep 17 00:00:00 2001 From: Ian Dominno <104934992+iadomi@users.noreply.github.com> Date: Thu, 27 Feb 2025 17:27:27 -0500 Subject: [PATCH] test: consolidate testing files (#445) * test: consolidate testing files Signed-off-by: Ian Dominno * fix: remove parent temp folder Signed-off-by: chjmil * fix: make file deletion os-agnostic Signed-off-by: chjmil --------- Signed-off-by: Ian Dominno Signed-off-by: chjmil Co-authored-by: chjmil --- test/acr_new_test.go | 149 ------ test/acr_test.go | 85 ---- test/admin_new_test.go | 76 --- test/admin_test.go | 81 ---- test/azure_netapp_test.go | 88 ---- test/default_integration_plan_test.go | 431 ------------------ ..._plan_new_test.go => default_unit_test.go} | 56 +++ test/helpers.go | 12 +- test/nodepool_test.go | 61 --- test/non_default_unit_test.go | 383 ++++++++++++++++ test/postgres_test.go | 101 ---- test/rbac_test.go | 76 --- 12 files changed, 448 insertions(+), 1151 deletions(-) delete mode 100644 test/acr_new_test.go delete mode 100644 test/acr_test.go delete mode 100644 test/admin_new_test.go delete mode 100644 test/admin_test.go delete mode 100644 test/azure_netapp_test.go delete mode 100644 test/default_integration_plan_test.go rename test/{default_integration_plan_new_test.go => default_unit_test.go} (92%) delete mode 100644 test/nodepool_test.go create mode 100644 test/non_default_unit_test.go delete mode 100644 test/postgres_test.go delete mode 100644 test/rbac_test.go diff --git a/test/acr_new_test.go b/test/acr_new_test.go deleted file mode 100644 index 71f9b976..00000000 --- a/test/acr_new_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package test - -import ( - "testing" - - "github.com/gruntwork-io/terratest/modules/terraform" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -//const ACR_STATEFUL_SOURCE = "azurerm_container_registry.acr[0]" - -// Verify Acr disabled stuff -func TestPlanAcrDisabledNew(t *testing.T) { - acrDisabledTests := map[string]testCase{ - "acrDisabledTest": { - expected: "", - resourceMapName: "azurerm_container_registry.acr[0]", - attributeJsonPath: "{$}", - retriever: resourceRetrieverRequireNotExist, - message: "Azure Container Registry (ACR) present when it should not be", - }, - } - - variables := getDefaultPlanVars(t) - variables["create_container_registry"] = false - variables["container_registry_admin_enabled"] = true - plan, err := initPlanWithVariables(t, variables) - require.NotNil(t, plan) - require.NoError(t, err) - - for name, tc := range acrDisabledTests { - t.Run(name, func(t *testing.T) { - runTest(t, tc, plan) - }) - } -} - -// Verify Acr standard stuff -func TestPlanACRStandardNew(t *testing.T) { - acrStandardTests := map[string]testCase{ - "acrGeoRepsNotExistTest": { - expected: "[]", - resourceMapName: "azurerm_container_registry.acr[0]", - attributeJsonPath: "{$.georeplications}", - message: "Geo-replications found when they should not be present", - }, - "nameTest": { - resourceMapName: "azurerm_container_registry.acr[0]", - attributeJsonPath: "{$.name}", - assertFunction: assert.Contains, - message: "ACR name does not contain 'acr'", - }, - "skuTest": { - expected: "Standard", - resourceMapName: "azurerm_container_registry.acr[0]", - attributeJsonPath: "{$.sku}", - message: "Unexpected ACR SKU value", - }, - "adminEnabledTest": { - expected: "true", - resourceMapName: "azurerm_container_registry.acr[0]", - attributeJsonPath: "{$.admin_enabled}", - message: "Unexpected ACR admin_enabled value", - }, - } - - variables := getDefaultPlanVars(t) - variables["create_container_registry"] = true - variables["container_registry_admin_enabled"] = true - variables["container_registry_sku"] = "Standard" - plan, err := initPlanWithVariables(t, variables) - require.NotNil(t, plan) - require.NoError(t, err) - - resource, resourceExists := plan.ResourcePlannedValuesMap["azurerm_container_registry.acr[0]"] - require.True(t, resourceExists) - acrName, nameExists := resource.AttributeValues["name"].(string) - require.True(t, nameExists) - nameTestCase := acrStandardTests["nameTest"] - nameTestCase.expected = acrName - acrStandardTests["nameTest"] = nameTestCase - - for name, tc := range acrStandardTests { - t.Run(name, func(t *testing.T) { - runTest(t, tc, plan) - }) - } -} - -// Verify Acr premium stuff -func TestPlanACRPremiumNew(t *testing.T) { - acrPremiumTests := map[string]testCase{ - "locationsTest": { - expected: "southeastus3 southeastus5", - resourceMapName: "azurerm_container_registry.acr[0]", - attributeJsonPath: "{$.georeplications[*].location}", - message: "Geo-replications do not match expected values", - }, - "nameTest": { - resourceMapName: "azurerm_container_registry.acr[0]", - attributeJsonPath: "{$.name}", - assertFunction: assert.Contains, - message: "ACR name does not contain 'acr'", - }, - "skuTest": { - expected: "Premium", - resourceMapName: "azurerm_container_registry.acr[0]", - attributeJsonPath: "{$.sku}", - message: "Unexpected ACR SKU value", - }, - "adminEnabledTest": { - expected: "true", - resourceMapName: "azurerm_container_registry.acr[0]", - attributeJsonPath: "{$.admin_enabled}", - message: "Unexpected ACR admin_enabled value", - }, - } - - variables := getDefaultPlanVars(t) - variables["create_container_registry"] = true - variables["container_registry_admin_enabled"] = true - variables["container_registry_sku"] = "Premium" - variables["container_registry_geo_replica_locs"] = []string{"southeastus5", "southeastus3"} - plan, err := initPlanWithVariables(t, variables) - require.NotNil(t, plan) - require.NoError(t, err) - - resource, resourceExists := plan.ResourcePlannedValuesMap["azurerm_container_registry.acr[0]"] - require.True(t, resourceExists) - acrName, nameExists := resource.AttributeValues["name"].(string) - require.True(t, nameExists) - nameTestCase := acrPremiumTests["nameTest"] - nameTestCase.expected = acrName - acrPremiumTests["nameTest"] = nameTestCase - - for name, tc := range acrPremiumTests { - t.Run(name, func(t *testing.T) { - runTest(t, tc, plan) - }) - } -} - -func resourceRetrieverRequireNotExist(t *testing.T, plan *terraform.PlanStruct, resourceMapName string, - attributeJsonPath string) (string, error) { - _, exists := plan.ResourcePlannedValuesMap[resourceMapName] - assert.False(t, exists, resourceMapName+"."+attributeJsonPath+" should not be present") - return "", nil -} diff --git a/test/acr_test.go b/test/acr_test.go deleted file mode 100644 index 7c1d8f26..00000000 --- a/test/acr_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package test - -import ( - "strings" - "testing" - - tfjson "github.com/hashicorp/terraform-json" - "github.com/stretchr/testify/assert" -) - -const ACR_STATEFUL_SOURCE = "azurerm_container_registry.acr[0]" - -func TestPlanACRDisabled(t *testing.T) { - t.Parallel() - - // Initialize the default variables map - variables := getDefaultPlanVars(t) - variables["create_container_registry"] = false - variables["container_registry_admin_enabled"] = true - plan, err := initPlanWithVariables(t, variables) - assert.NoError(t, err) - - _, acrExists := plan.ResourcePlannedValuesMap[ACR_STATEFUL_SOURCE] - assert.False(t, acrExists, "Azure Container Registry (ACR) present when it should not be") -} - -func TestPlanACRStandard(t *testing.T) { - t.Parallel() - - // Initialize the default variables map - variables := getDefaultPlanVars(t) - variables["create_container_registry"] = true - variables["container_registry_admin_enabled"] = true - variables["container_registry_sku"] = "Standard" - plan, err := initPlanWithVariables(t, variables) - assert.NoError(t, err) - - acrResource := plan.ResourcePlannedValuesMap[ACR_STATEFUL_SOURCE] - commonAssertions(t, variables, acrResource) - - geoReplications, err := getJsonPathFromStateResource(t, acrResource, "{$.georeplications}") - assert.NoError(t, err) - assert.Equal(t, "[]", geoReplications, "Geo-replications found when they should not be present") -} - -func TestPlanACRPremium(t *testing.T) { - t.Parallel() - - variables := getDefaultPlanVars(t) - variables["create_container_registry"] = true - variables["container_registry_admin_enabled"] = true - variables["container_registry_sku"] = "Premium" - variables["container_registry_geo_replica_locs"] = []string{"southeastus5", "southeastus3"} - plan, err := initPlanWithVariables(t, variables) - assert.NoError(t, err) - - acrResource := plan.ResourcePlannedValuesMap[ACR_STATEFUL_SOURCE] - commonAssertions(t, variables, acrResource) - - // Validate geo-replication locations - actualGeoReplications, err := getJsonPathFromStateResource(t, acrResource, "{$.georeplications[*].location}") - assert.NoError(t, err) - expectedGeoReplications := variables["container_registry_geo_replica_locs"].([]string) - assert.ElementsMatch(t, expectedGeoReplications, strings.Fields(actualGeoReplications), "Geo-replications do not match expected values") -} - -func commonAssertions(t *testing.T, variables map[string]interface{}, acrResource *tfjson.StateResource) { - assert.True(t, acrResource != nil, "Azure Container Registry (ACR) not found in the Terraform plan") - - acrName, nameExists := acrResource.AttributeValues["name"].(string) - assert.True(t, nameExists, "ACR name not found or is not a string") - assert.Contains(t, acrName, "acr", "ACR name does not contain 'acr'") - - acrSKU, skuExists := acrResource.AttributeValues["sku"].(string) - assert.True(t, skuExists, "ACR SKU not found or is not a string") - expectedSKU, ok := variables["container_registry_sku"].(string) - assert.True(t, ok, "'container_registry_sku' not found or is not a string") - assert.Equal(t, expectedSKU, acrSKU, "Unexpected ACR SKU value") - - adminEnabled, adminExists := acrResource.AttributeValues["admin_enabled"].(bool) - assert.True(t, adminExists, "ACR admin_enabled not found or is not a boolean") - expectedAdminEnabled, ok := variables["container_registry_admin_enabled"].(bool) - assert.True(t, ok, "'container_registry_admin_enabled' not found or is not a boolean") - assert.Equal(t, expectedAdminEnabled, adminEnabled, "Unexpected ACR admin_enabled value") -} diff --git a/test/admin_new_test.go b/test/admin_new_test.go deleted file mode 100644 index 7b7af143..00000000 --- a/test/admin_new_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package test - -import ( - "fmt" - "strings" - "testing" - - "github.com/gruntwork-io/terratest/modules/random" - "github.com/gruntwork-io/terratest/modules/terraform" - "github.com/stretchr/testify/require" -) - -// Verify Acr disabled stuff -// TestAdminAccess verifies that NSG rules for admin access are correctly applied in the Terraform plan. -func TestAdminAccessNew(t *testing.T) { - adminAccessTests := map[string]testCase{ - "defaultCidrTest": { - expected: "[123.45.67.89/16]", - resourceMapName: "default_public_access_cidrs", - retriever: getVariablesFromPlan, - message: "Mismatch in default_public_access_cidrs", - }, - "clusterCidrTest": { - expected: "", - resourceMapName: "cluster_endpoint_public_access_cidrs", - retriever: getVariablesFromPlan, - message: "Mismatch in cluster_endpoint_public_access_cidrs", - }, - "vmCidrTest": { - expected: "", - resourceMapName: "vm_public_access_cidrs", - retriever: getVariablesFromPlan, - message: "Mismatch in vm_public_access_cidrs", - }, - "postgresCidrTest": { - expected: "", - resourceMapName: "vm_public_access_cidrs", - retriever: getVariablesFromPlan, - message: "Mismatch in postgres_public_access_cidrs", - }, - "acrCidrTest": { - expected: "", - resourceMapName: "acr_public_access_cidrs", - retriever: getVariablesFromPlan, - message: "Mismatch in acr_public_access_cidrs", - }, - } - - // Generate a unique prefix for test isolation - uniquePrefix := strings.ToLower(random.UniqueId()) - variables := getDefaultPlanVars(t) - variables["prefix"] = "terratest-" + uniquePrefix - variables["location"] = "eastus2" - // Using a dummy CIDR for testing purposes - variables["default_public_access_cidrs"] = []interface{}{"123.45.67.89/16"} - plan, err := initPlanWithVariables(t, variables) - require.NotNil(t, plan) - require.NoError(t, err) - - for name, tc := range adminAccessTests { - t.Run(name, func(t *testing.T) { - runTest(t, tc, plan) - }) - } -} - -// Retriever function. Note the unused jsonPath parameter -func getVariablesFromPlan(t *testing.T, plan *terraform.PlanStruct, outputName string, jsonPath string) (string, error) { - output, exists := plan.RawPlan.Variables[outputName] - if !exists { - return "nil", nil - } - require.NotNil(t, output) - value := fmt.Sprintf("%v", output.Value) - return value, nil -} diff --git a/test/admin_test.go b/test/admin_test.go deleted file mode 100644 index 1df95c45..00000000 --- a/test/admin_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package test - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "github.com/gruntwork-io/terratest/modules/random" - "github.com/gruntwork-io/terratest/modules/terraform" - test_structure "github.com/gruntwork-io/terratest/modules/test-structure" - "github.com/stretchr/testify/assert" -) - -// TestAdminAccess verifies that NSG rules for admin access are correctly applied in the Terraform plan. -func TestAdminAccess(t *testing.T) { - t.Parallel() - - // Generate a unique prefix for test isolation - uniquePrefix := strings.ToLower(random.UniqueId()) - p := "../examples/sample-input-defaults.tfvars" - - var variables map[string]interface{} - terraform.GetAllVariablesFromVarFile(t, p, &variables) - - // Add required test variables - variables["prefix"] = "terratest-" + uniquePrefix - variables["location"] = "eastus2" - // Using a dummy CIDR for testing purposes - variables["default_public_access_cidrs"] = []interface{}{"123.45.67.89/16"} - - // Create a temporary Terraform plan file - planFileName := "testplan-" + uniquePrefix + ".tfplan" - planFilePath := filepath.Join("/tmp/", planFileName) - defer os.Remove(planFilePath) // Cleanup after test execution - - // Copy the terraform folder to a temp folder - tempTestFolder := test_structure.CopyTerraformFolderToTemp(t, "../", "") - defer os.RemoveAll(tempTestFolder) - - // Configure Terraform options - terraformOptions := &terraform.Options{ - TerraformDir: tempTestFolder, - Vars: variables, - PlanFilePath: planFilePath, - NoColor: true, - } - - plan := terraform.InitAndPlanAndShowWithStruct(t, terraformOptions) - - actualDefaultCidr, hasDefaultCidr := plan.RawPlan.Variables["default_public_access_cidrs"] - actualClusterCidr, hasClusterCidr := plan.RawPlan.Variables["cluster_endpoint_public_access_cidrs"] - actualVmCidr, hasVmCidr := plan.RawPlan.Variables["vm_public_access_cidrs"] - actualPostgresCidr, hasPostgresCidr := plan.RawPlan.Variables["postgres_public_access_cidrs"] - actualAcrCidr, hasAcrCidr := plan.RawPlan.Variables["acr_public_access_cidrs"] - - // Validate Default Public Access CIDRs - expectedDefaultCidr := variables["default_public_access_cidrs"] - assert.True(t, hasDefaultCidr, "default_public_access_cidrs should exist in plan") - assert.Equal(t, expectedDefaultCidr, actualDefaultCidr.Value, "Mismatch in default_public_access_cidrs") - - // Validate Cluster Endpoint Public Access CIDRs - expectedClusterCidr := variables["cluster_endpoint_public_access_cidrs"] - assert.True(t, hasClusterCidr, "cluster_endpoint_public_access_cidrs should exist in plan") - assert.Equal(t, expectedClusterCidr, actualClusterCidr.Value, "Mismatch in cluster_endpoint_public_access_cidrs") - - // Validate VM Public Access CIDRs - expectedVmCidr := variables["vm_public_access_cidrs"] - assert.True(t, hasVmCidr, "vm_public_access_cidrs should exist in plan") - assert.Equal(t, expectedVmCidr, actualVmCidr.Value, "Mismatch in vm_public_access_cidrs") - - // Validate PostgreSQL Public Access CIDRs - expectedPostgresCidr := variables["postgres_public_access_cidrs"] - assert.True(t, hasPostgresCidr, "postgres_public_access_cidrs should exist in plan") - assert.Equal(t, expectedPostgresCidr, actualPostgresCidr.Value, "Mismatch in postgres_public_access_cidrs") - - // Validate ACR Public Access CIDRs - expectedAcrCidr := variables["acr_public_access_cidrs"] - assert.True(t, hasAcrCidr, "acr_public_access_cidrs should exist in plan") - assert.Equal(t, expectedAcrCidr, actualAcrCidr.Value, "Mismatch in acr_public_access_cidrs") -} diff --git a/test/azure_netapp_test.go b/test/azure_netapp_test.go deleted file mode 100644 index fe84faf2..00000000 --- a/test/azure_netapp_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// Test the default variables when using the sample-input-defaults.tfvars file -// with storage_type set to "ha". This should engage the Azure NetApp Files module, -// with the default values as tested herein. -func TestAzureNetApp(t *testing.T) { - tests := map[string]testCase{ - "accountExists": { - expected: `nil`, - resourceMapName: "module.netapp[0].azurerm_netapp_account.anf", - attributeJsonPath: "{$}", - assertFunction: assert.NotEqual, - }, - "poolExists": { - expected: `nil`, - resourceMapName: "module.netapp[0].azurerm_netapp_pool.anf", - attributeJsonPath: "{$}", - assertFunction: assert.NotEqual, - }, - "poolServiceLevel": { - expected: `Premium`, - resourceMapName: "module.netapp[0].azurerm_netapp_pool.anf", - attributeJsonPath: "{$.service_level}", - }, - "poolSize": { - expected: `4`, - resourceMapName: "module.netapp[0].azurerm_netapp_pool.anf", - attributeJsonPath: "{$.size_in_tb}", - }, - "volumeExists": { - expected: `nil`, - resourceMapName: "module.netapp[0].azurerm_netapp_volume.anf", - attributeJsonPath: "{$}", - assertFunction: assert.NotEqual, - }, - "volumeProtocols": { - expected: `["NFSv4.1"]`, - resourceMapName: "module.netapp[0].azurerm_netapp_volume.anf", - attributeJsonPath: "{$.protocols}", - }, - "volumeServiceLevel": { - expected: `Premium`, - resourceMapName: "module.netapp[0].azurerm_netapp_volume.anf", - attributeJsonPath: "{$.service_level}", - }, - "volumePath": { - expected: `export`, - resourceMapName: "module.netapp[0].azurerm_netapp_volume.anf", - attributeJsonPath: "{$.volume_path}", - assertFunction: assert.Contains, - }, - "volumeNetworkFeatures": { - expected: `Basic`, - resourceMapName: "module.netapp[0].azurerm_netapp_volume.anf", - attributeJsonPath: "{$.network_features}", - }, - "subnetExists": { - expected: `nil`, - resourceMapName: "module.vnet.azurerm_subnet.subnet[\"netapp\"]", - attributeJsonPath: "{$}", - assertFunction: assert.NotEqual, - }, - } - - // Prepare to generate the plan - varsFilePath := "../examples/sample-input-defaults.tfvars" - variables := getPlanVars(t, varsFilePath) - variables["storage_type"] = "ha" - - // Generate the plan - plan, err := initPlanWithVariables(t, variables) - require.NotNil(t, plan) - require.NoError(t, err) - - // Run the tests - for name, tc := range tests { - t.Run(name, func(t *testing.T) { - runTest(t, tc, plan) - }) - } -} diff --git a/test/default_integration_plan_test.go b/test/default_integration_plan_test.go deleted file mode 100644 index dd4859c0..00000000 --- a/test/default_integration_plan_test.go +++ /dev/null @@ -1,431 +0,0 @@ -package test - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "github.com/gruntwork-io/terratest/modules/random" - "github.com/gruntwork-io/terratest/modules/terraform" - test_structure "github.com/gruntwork-io/terratest/modules/test-structure" - tfjson "github.com/hashicorp/terraform-json" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -type NodePool struct { - Name string - MachineType string - OsDiskSize float64 - MinNodes float64 - MaxNodes float64 - MaxPods float64 - NodeTaints []string - NodeLabels map[string]string - AvailabilityZones []string - FipsEnabled bool -} - -type Subnet struct { - prefixes []interface{} - serviceEndpoints []interface{} - privateEndpointNetworkPolicies string - privateLinkServiceNetworkPoliciesEnabled bool - serviceDelegations map[string]interface{} -} - -// Test the default variables when using the sample-input-defaults.tfvars file. -// Verify that the tfplan is using the default variables from the CONFIG-VARS -func TestDefaults(t *testing.T) { - t.Parallel() - - uniquePrefix := strings.ToLower(random.UniqueId()) - p := "../examples/sample-input-defaults.tfvars" - - var variables map[string]interface{} - terraform.GetAllVariablesFromVarFile(t, p, &variables) - - // add the required variables - variables["prefix"] = "terratest-" + uniquePrefix - variables["location"] = "eastus2" - // Using a dummy CIDR for testing purposes - variables["default_public_access_cidrs"] = []string{"123.45.67.89/16"} - - // Create a temporary file in the default temp directory - planFileName := "testplan-" + uniquePrefix + ".tfplan" - planFilePath := filepath.Join(os.TempDir(), planFileName) - _, err := os.Create(planFilePath) - require.NoError(t, err) - defer os.Remove(planFilePath) // Ensure file is removed on exit - - // Copy the terraform folder to a temp folder - tempTestFolder := test_structure.CopyTerraformFolderToTemp(t, "../", "") - defer os.RemoveAll(tempTestFolder) - - // Configure Terraform setting up a path to Terraform code. - terraformOptions := &terraform.Options{ - // The path to where our Terraform code is located. - TerraformDir: tempTestFolder, - - // Variables to pass to our Terraform code using -var options. - Vars: variables, - - // Configure a plan file path so we can introspect the plan and make assertions about it. - PlanFilePath: planFilePath, - - // Remove color codes to clean up output - NoColor: true, - } - - plan := terraform.InitAndPlanAndShowWithStruct(t, terraformOptions) - // cluster := plan.ResourcePlannedValuesMap["module.aks.azurerm_kubernetes_cluster.aks"] - - // VAI: TEST MOVED TO TEST TABLE - //// vnet_address_space - //expectedVnetAddress := []interface{}{"192.168.0.0/16"} - //vnetResource := plan.ResourcePlannedValuesMap["module.vnet.azurerm_virtual_network.vnet[0]"] - //vnetAttributes := vnetResource.AttributeValues["address_space"].([]interface{}) - //assert.Equal(t, expectedVnetAddress, vnetAttributes) - - // aks Subnets - expectedAKSSubnet := &Subnet{ - prefixes: []interface{}{"192.168.0.0/23"}, - serviceEndpoints: []interface{}{"Microsoft.Sql"}, - privateEndpointNetworkPolicies: "Disabled", - privateLinkServiceNetworkPoliciesEnabled: false, - serviceDelegations: nil, - } - verifySubnets(t, plan.ResourcePlannedValuesMap["module.vnet.azurerm_subnet.subnet[\"aks\"]"], expectedAKSSubnet) - - // misc subnet - expectedMiscSubnet := &Subnet{ - prefixes: []interface{}{"192.168.2.0/24"}, - serviceEndpoints: []interface{}{"Microsoft.Sql"}, - privateEndpointNetworkPolicies: "Disabled", - privateLinkServiceNetworkPoliciesEnabled: false, - serviceDelegations: nil, - } - verifySubnets(t, plan.ResourcePlannedValuesMap["module.vnet.azurerm_subnet.subnet[\"misc\"]"], expectedMiscSubnet) - - // VAI: TEST MOVED TO TEST TABLE - //// cluster_egress_type - //var expectedClusterEgressType interface{} = "loadBalancer" - //egressType := cluster.AttributeValues["network_profile"] - //actualEgressType := egressType.([]interface{})[0].(map[string]interface{})["outbound_type"] - //assert.Equal(t, expectedClusterEgressType, actualEgressType, "Unexpected Cluster Egress Type") - - // VAI: TEST MOVED TO TEST TABLE - //// aks_network_plugin - //var expectedNetworkPlugin interface{} = "kubenet" - //networkPlugin := cluster.AttributeValues["network_profile"] - //actualNetworkPlugin := networkPlugin.([]interface{})[0].(map[string]interface{})["network_plugin"] - //assert.Equal(t, expectedNetworkPlugin, actualNetworkPlugin, "Unexpected Network Plugin") - - // aks_network_policy cannot be tested since it is set after the apply. - /*var expectedNetworkPolicy interface{} = "calico" - networkPolicy := cluster.AttributeValues["network_profile"] - actualNetworkPolicy := networkPolicy.([]interface{})[0].(map[string]interface{})["network_policy"] - assert.Equal(t, expectedNetworkPolicy, actualNetworkPolicy, "Unexpected Network Policy") - - // aks_network_plugin_mode this cannot be tested since it defaults to null - /*var expectedNetworkPluginMode interface{} = "overlay" - networkPluginMode := cluster.AttributeValues["network_profile"] - actualNetworkPluginMode := networkPluginMode.([]interface{})[0].(map[string]interface{})["network_plugin_mode"] - assert.Equal(t, expectedNetworkPluginMode, actualNetworkPluginMode, "Unexpected Network Plugin Mode") */ - - // partner_id - Not present in tfplan - - // create_static_kubeconfig - // Assert that the Cluster Role Binding and Service Account objects - // are present in the output. create_static_kubeconfig=false would - // not contain these objects. - // CHJMIL: TEST MOVED TO TEST TABLE - // kubeconfigCRBResource := plan.ResourcePlannedValuesMap["module.kubeconfig.kubernetes_cluster_role_binding.kubernetes_crb[0]"] - // assert.NotNil(t, kubeconfigCRBResource, "Kubeconfig CRB object should not be nil") - // kubeconfigSAResource := plan.ResourcePlannedValuesMap["module.kubeconfig.kubernetes_service_account.kubernetes_sa[0]"] - // assert.NotNil(t, kubeconfigSAResource, "Kubeconfig Service Account object should not be nil") - - // VAI: TEST MOVED TO TEST TABLE - //// kubernetes_version - //k8sVersion := cluster.AttributeValues["kubernetes_version"] - //assert.Equal(t, "1.30", k8sVersion, "Unexpected Kubernetes version") - - // create_jump_vm - // Verify that the jump vm resource is not nil - // jumpVM := plan.ResourcePlannedValuesMap["module.jump[0].azurerm_linux_virtual_machine.vm"] - // CHJMIL: TEST MOVED TO TEST TABLE - // assert.NotNil(t, jumpVM, "Jump VM should be created") - - // create_jump_public_ip - // jumpPublicIP := plan.ResourcePlannedValuesMap["module.jump[0].azurerm_public_ip.vm_ip[0]"] - - // assert.NotNil(t, jumpPublicIP, "Jump VM public IP should exist") - - // enable_jump_public_static_ip - // assert.Equal(t, "Static", jumpPublicIP.AttributeValues["allocation_method"], "Jump VM should use static IP") - - // jump_vm_admin - // assert.Equal(t, "jumpuser", jumpVM.AttributeValues["admin_username"], "Unexpected jump VM admin username") - - // jump_vm_machine_type - // assert.Equal(t, "Standard_B2s", jumpVM.AttributeValues["size"], "Unexpected jump VM machine type") - - // CHJMIL: TEST MOVED TO TEST TABLE - // jump_rwx_filestore_path - // assert.Equal(t, "/viya-share", plan.RawPlan.OutputChanges["jump_rwx_filestore_path"].After.(string)) - - // CHJMIL: TEST MOVED TO TEST TABLE - // prefix - // assert.Equal(t, variables["prefix"], plan.RawPlan.OutputChanges["prefix"].After.(string)) - - // iadomi: TEST MOVED TO TEST TABLE - // location - // module.aks.data.azurerm_public_ip.cluster_public_ip[0] location is set after apply. - // locationResources := []string{ - // "azurerm_network_security_group.nsg[0]", - // "azurerm_resource_group.aks_rg[0]", - // "azurerm_user_assigned_identity.uai[0]", - // "module.aks.azurerm_kubernetes_cluster.aks", - // "module.jump[0].azurerm_linux_virtual_machine.vm", - // "module.jump[0].azurerm_network_interface.vm_nic", - // "module.jump[0].azurerm_public_ip.vm_ip[0]", - // "module.nfs[0].azurerm_linux_virtual_machine.vm", - // "module.nfs[0].azurerm_managed_disk.vm_data_disk[0]", - // "module.nfs[0].azurerm_managed_disk.vm_data_disk[1]", - // "module.nfs[0].azurerm_managed_disk.vm_data_disk[2]", - // "module.nfs[0].azurerm_managed_disk.vm_data_disk[3]", - // "module.nfs[0].azurerm_network_interface.vm_nic", - // "module.vnet.azurerm_virtual_network.vnet[0]", - // } - // for _, value := range locationResources { - // locationResource := plan.ResourcePlannedValuesMap[value] - // locationAttributes := locationResource.AttributeValues["location"] - // assert.Equal(t, variables["location"], locationAttributes, "Unexpected location") - // } - // CHJMIL: TEST MOVED TO TEST TABLE - // assert.Equal(t, variables["location"], plan.RawPlan.OutputChanges["location"].After.(string), "Unexpected location") - - // tags - defaults to empty so there is nothing to test. If we wanted to test it, this is how we would - // aksTags := cluster.AttributeValues["tags"] - // assert.Equal(t, aksTags, map[string]interface{}(map[string]interface{}{"test": "test"}), "Unexpected AKS Tags") - - // VAI: TEST MOVED TO TEST TABLE - //// aks_identity - //userAssignedIdentity := plan.ResourcePlannedValuesMap["azurerm_user_assigned_identity.uai[0]"] - //assert.NotNil(t, userAssignedIdentity, "The User Identity should exist.") - - // ssh_public_key - // assert.True(t, testSSHKey(t, cluster), "SSH Key should exist") - - // CHJMIL: TEST MOVED TO TEST TABLE - // cluster_api_mode - // assert.Equal(t, "public", plan.RawPlan.OutputChanges["cluster_api_mode"].After.(string)) - - // aks_cluster_private_dns_zone_id - defaults to empty, only known after apply - - // VAI: TEST MOVED TO TEST TABLE - //// aks_cluster_sku_tier - //skuTier := cluster.AttributeValues["sku_tier"] - //assert.Equal(t, skuTier, "Free", "Unexpected aks_cluster_sku_tier") - - // VAI: TEST MOVED TO TEST TABLE - //// cluster_support_tier - //supportPlan := cluster.AttributeValues["support_plan"] - //assert.Equal(t, supportPlan, "KubernetesOfficial", "Unexpected cluster_support_tier") - - // Additional Node Pools - TEST MOVED TO TEST TABLE - // statelessNodePool := plan.ResourcePlannedValuesMap["module.node_pools[\"stateless\"].azurerm_kubernetes_cluster_node_pool.autoscale_node_pool[0]"] - // statelessStruct := &NodePool{ - // MachineType: "Standard_D4s_v5", - // OsDiskSize: 200, - // MinNodes: 0, - // MaxNodes: 5, - // MaxPods: 110, - // NodeTaints: []string{"workload.sas.com/class=stateless:NoSchedule"}, - // NodeLabels: map[string]string{ - // "workload.sas.com/class": "stateless", - // }, - // AvailabilityZones: []string{"1"}, - // FipsEnabled: false, - // } - // verifyNodePools(t, statelessNodePool, statelessStruct) - - // statefulNodePool := plan.ResourcePlannedValuesMap["module.node_pools[\"stateful\"].azurerm_kubernetes_cluster_node_pool.autoscale_node_pool[0]"] - // statefulStruct := &NodePool{ - // MachineType: "Standard_D4s_v5", - // OsDiskSize: 200, - // MinNodes: 0, - // MaxNodes: 3, - // MaxPods: 110, - // NodeTaints: []string{"workload.sas.com/class=stateful:NoSchedule"}, - // NodeLabels: map[string]string{ - // "workload.sas.com/class": "stateful", - // }, - // AvailabilityZones: []string{"1"}, - // FipsEnabled: false, - // } - // verifyNodePools(t, statefulNodePool, statefulStruct) - // casNodePool := plan.ResourcePlannedValuesMap["module.node_pools[\"cas\"].azurerm_kubernetes_cluster_node_pool.autoscale_node_pool[0]"] - // casStruct := &NodePool{ - // MachineType: "Standard_E16ds_v5", - // OsDiskSize: 200, - // MinNodes: 0, - // MaxNodes: 5, - // MaxPods: 110, - // NodeTaints: []string{"workload.sas.com/class=cas:NoSchedule"}, - // NodeLabels: map[string]string{ - // "workload.sas.com/class": "cas", - // }, - // AvailabilityZones: []string{"1"}, - // FipsEnabled: false, - // } - // verifyNodePools(t, casNodePool, casStruct) - - // computeNodePool := plan.ResourcePlannedValuesMap["module.node_pools[\"compute\"].azurerm_kubernetes_cluster_node_pool.autoscale_node_pool[0]"] - // computeStruct := &NodePool{ - // MachineType: "Standard_D4ds_v5", - // OsDiskSize: 200, - // MinNodes: 1, - // MaxNodes: 5, - // MaxPods: 110, - // NodeTaints: []string{"workload.sas.com/class=compute:NoSchedule"}, - // NodeLabels: map[string]string{ - // "workload.sas.com/class": "compute", - // "launcher.sas.com/prepullImage": "sas-programming-environment", - // }, - // AvailabilityZones: []string{"1"}, - // FipsEnabled: false, - // } - // verifyNodePools(t, computeNodePool, computeStruct) - - // VAI: TEST MOVED TO TEST TABLE - //// storage_type - //// when storage_type is standard, we should have nfs stuff - //// make sure module.nfs[0].azurerm_linux_virtual_machine.vm exists - //nfsVM := plan.ResourcePlannedValuesMap["module.nfs[0].azurerm_linux_virtual_machine.vm"] - //assert.NotNil(t, nfsVM, "NFS VM should be created") - //assert.Equal(t, "nfsuser", nfsVM.AttributeValues["admin_username"], "Unexpected NFS Admin Username") - //assert.Equal(t, "Standard_D4s_v5", nfsVM.AttributeValues["size"], "Unexpected NFS VM Size") - - // create_nfs_public_ip - // nfsPublicIP := plan.ResourcePlannedValuesMap["module.nfs[0].azurerm_public_ip.vm_ip[0]"] - // assert.Nil(t, nfsPublicIP, "NFS Public IP should not be created when create_nfs_public_ip=false") - - // nfs_raid_disk_type - // when storage_type is standard, we should have four nfs data disks - // make sure all four module.nfs[0].azurerm_managed_disk.vm_data_disk[i] resources exist - // for i := 0; i < 4; i++ { - // nfsDataDisk := plan.ResourcePlannedValuesMap[fmt.Sprintf("module.nfs[0].azurerm_managed_disk.vm_data_disk[%d]", i)] - // assert.NotNil(t, nfsDataDisk, fmt.Sprintf("NFS Data Disk %d should be created for NFS VM", i)) - - // // make sure all four disks are using raid disk type Standard_LRS by default - // nfsDataDisk = plan.ResourcePlannedValuesMap[fmt.Sprintf("module.nfs[0].azurerm_managed_disk.vm_data_disk[%d]", i)] - // assert.Equal(t, "Standard_LRS", nfsDataDisk.AttributeValues["storage_account_type"], fmt.Sprintf("Unexpected NFS Raid Disk Type for disk %d", i)) - - // // make sure all four disks have default disk size of 256 gb - // nfsDataDisk = plan.ResourcePlannedValuesMap[fmt.Sprintf("module.nfs[0].azurerm_managed_disk.vm_data_disk[%d]", i)] - // assert.Equal(t, float64(256), nfsDataDisk.AttributeValues["disk_size_gb"], fmt.Sprintf("Unexpected NFS Raid Disk Size in GB for disk %d", i)) - // } - - // VAI: TEST MOVED TO TEST TABLE - //// nfs_vm_zone - //// defaults to null - //assert.Nil(t, nfsVM.AttributeValues["vm_zone"], "Unexpected NFS VM_Zone; should default to null ") - - // enable_nfs_public_static_ip - // only used with create_nfs_public_ip=true - - // aks - TEST MOVED TO TEST TABLE - // aks := plan.ResourcePlannedValuesMap["module.aks.azurerm_kubernetes_cluster.aks"] - // aad_rbac := aks.AttributeValues["azure_active_directory_role_based_access_control"] - // assert.Empty(t, aad_rbac, "Unexpected azure_active_directory_role_based_access_control; should be empty by default") -} - -// func testSSHKey(t *testing.T, cluster *tfjson.StateResource) bool { -// key, err := getJsonPathFromStateResource(t, cluster, "{$.linux_profile[0].ssh_key[0].key_data}") -// assert.NoError(t, err) -// return key != "" -// } - -// TEST MOVED TO TEST TABLE -// func verifyNodePools(t *testing.T, nodePool *tfjson.StateResource, expectedValues *NodePool) { -// // machine_type -// assert.Equal(t, expectedValues.MachineType, nodePool.AttributeValues["vm_size"], "Unexpected machine_type.") - -// // os_disk_size -// assert.Equal(t, expectedValues.OsDiskSize, nodePool.AttributeValues["os_disk_size_gb"], "Unexpected os_disk_size.") - -// // min_nodes -// assert.Equal(t, expectedValues.MinNodes, nodePool.AttributeValues["min_count"], "Unexpected min_nodes.") - -// // max_nodes -// assert.Equal(t, expectedValues.MaxNodes, nodePool.AttributeValues["max_count"], "Unexpected max_nodes.") - -// // max_pods -// assert.Equal(t, expectedValues.MaxPods, nodePool.AttributeValues["max_pods"], "Unexpected max_pods.") - -// // node_taints -// for index, nodeTaint := range expectedValues.NodeTaints { -// assert.Equal(t, nodeTaint, nodePool.AttributeValues["node_taints"].([]interface{})[index].(string), "Unexpected Node Taints") -// } - -// // node_labels -// nodeLabelsStatus := true -// nodeLabels := nodePool.AttributeValues["node_labels"] -// // Convert the interface {}(map[string]interface {}) to JSON string -// j, err := json.Marshal(nodeLabels) -// if err != nil { -// t.Log("Error parsing tfplan's Node Labels: ", err) -// nodeLabelsStatus = false -// } -// // Unmarshal the JSON string into the map -// var result map[string]string -// err = json.Unmarshal(j, &result) -// if err != nil { -// t.Log("Error unmarshaling Node Labels Json string: ", err) -// nodeLabelsStatus = false -// } -// // If no previous errors, verify that the maps are equal -// if nodeLabelsStatus { -// assert.True(t, reflect.DeepEqual(expectedValues.NodeLabels, result), "Unexpected Node Labels") -// } else { -// assert.Fail(t, "Unexpected errors parsing Node Labels") -// } - -// // node_pools_availability_zone -// for index, az := range expectedValues.AvailabilityZones { -// assert.Equal(t, az, nodePool.AttributeValues["zones"].([]interface{})[index].(string), "Unexpected Availability Zones") -// } - -// // fips_enabled - TEST MOVED TO TEST TABLE -// // assert.Equal(t, expectedValues.FipsEnabled, nodePool.AttributeValues["fips_enabled"], "Unexpected fips_enabled.") - -// // node_pools_proximity_placement - Can't find in tfplan - -// } - -// Subnet func -func verifySubnets(t *testing.T, subnet *tfjson.StateResource, expectedValues *Subnet) { - // prefixes - assert.Equal(t, expectedValues.prefixes, subnet.AttributeValues["address_prefixes"], "Unexpected Subnet address_prefixes") - - // service_endpoints - assert.Equal(t, expectedValues.serviceEndpoints, subnet.AttributeValues["service_endpoints"], "Unexpected Subnet service endpoints") - - // private_endpoint_network_policies - // TODO figure out why these don't match the expected - // assert.Equal(t, expectedValues.privateEndpointNetworkPolicies, subnet.AttributeValues["private_endpoint_network_policies"], "Unexpected private_endpoint_network_policies") - - // private_link_service_network_policies_enabled - assert.Equal(t, expectedValues.privateLinkServiceNetworkPoliciesEnabled, subnet.AttributeValues["private_link_service_network_policies_enabled"], "Unexpected private_link_service_network_policies_enabled") - - // service_delegations - // If no sevice_delegations are set, verify that there is no service_delegations - // attribute in the resource. Otherwise, check that the attribute matches the expected - if expectedValues.serviceDelegations == nil { - assert.Nil(t, subnet.AttributeValues["service_delegations"], "Service delegations should be nil") - } else { - assert.Equal(t, expectedValues.serviceDelegations, subnet.AttributeValues["service_delegations"], "Unexpected service delegations") - } -} diff --git a/test/default_integration_plan_new_test.go b/test/default_unit_test.go similarity index 92% rename from test/default_integration_plan_new_test.go rename to test/default_unit_test.go index 9ef7a2a8..280a01c6 100644 --- a/test/default_integration_plan_new_test.go +++ b/test/default_unit_test.go @@ -5,8 +5,10 @@ package test import ( "fmt" + "strings" "testing" + "github.com/gruntwork-io/terratest/modules/random" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -660,3 +662,57 @@ func TestDefaultSubnets(t *testing.T) { }) } } + +// Verify Acr disabled stuff +// TestAdminAccess verifies that NSG rules for admin access are correctly applied in the Terraform plan. +func TestDefaultAdminAccess(t *testing.T) { + adminAccessTests := map[string]testCase{ + "defaultCidrTest": { + expected: "[123.45.67.89/16]", + resourceMapName: "default_public_access_cidrs", + retriever: getOutputsFromPlan, + message: "Mismatch in default_public_access_cidrs", + }, + "clusterCidrTest": { + expected: "", + resourceMapName: "cluster_endpoint_public_access_cidrs", + retriever: getOutputsFromPlan, + message: "Mismatch in cluster_endpoint_public_access_cidrs", + }, + "vmCidrTest": { + expected: "", + resourceMapName: "vm_public_access_cidrs", + retriever: getOutputsFromPlan, + message: "Mismatch in vm_public_access_cidrs", + }, + "postgresCidrTest": { + expected: "", + resourceMapName: "vm_public_access_cidrs", + retriever: getOutputsFromPlan, + message: "Mismatch in postgres_public_access_cidrs", + }, + "acrCidrTest": { + expected: "", + resourceMapName: "acr_public_access_cidrs", + retriever: getOutputsFromPlan, + message: "Mismatch in acr_public_access_cidrs", + }, + } + + // Generate a unique prefix for test isolation + uniquePrefix := strings.ToLower(random.UniqueId()) + variables := getDefaultPlanVars(t) + variables["prefix"] = "terratest-" + uniquePrefix + variables["location"] = "eastus2" + // Using a dummy CIDR for testing purposes + variables["default_public_access_cidrs"] = []interface{}{"123.45.67.89/16"} + plan, err := initPlanWithVariables(t, variables) + require.NotNil(t, plan) + require.NoError(t, err) + + for name, tc := range adminAccessTests { + t.Run(name, func(t *testing.T) { + runTest(t, tc, plan) + }) + } +} diff --git a/test/helpers.go b/test/helpers.go index e3a6deee..fd4a8ce1 100644 --- a/test/helpers.go +++ b/test/helpers.go @@ -2,6 +2,7 @@ package test import ( "bytes" + "fmt" "os" "path/filepath" "strings" @@ -51,11 +52,13 @@ func getJsonPathFromStateResource(t *testing.T, resource *tfjson.StateResource, } func getOutputsFromPlan(t *testing.T, plan *terraform.PlanStruct, outputName string, jsonPath string) (string, error) { - output, exists := plan.RawPlan.OutputChanges[outputName] + output, exists := plan.RawPlan.Variables[outputName] if !exists { return "nil", nil } - return output.After.(string), nil + require.NotNil(t, output) + value := fmt.Sprintf("%v", output.Value) + return value, nil } // getDefaultPlanVars returns a map of default terratest variables @@ -91,7 +94,10 @@ func initPlanWithVariables(t *testing.T, variables map[string]interface{}) (*ter // Copy the terraform folder to a temp folder tempTestFolder := test_structure.CopyTerraformFolderToTemp(t, "../", "") - defer os.RemoveAll(tempTestFolder) + // Get the path to the parent folder for clean up + tempTestFolderSlice := strings.Split(tempTestFolder, string(os.PathSeparator)) + tempTestFolderPath := strings.Join(tempTestFolderSlice[:len(tempTestFolderSlice)-1], string(os.PathSeparator)) + defer os.RemoveAll(tempTestFolderPath) // Set up Terraform options terraformOptions := &terraform.Options{ diff --git a/test/nodepool_test.go b/test/nodepool_test.go deleted file mode 100644 index c5dc86d4..00000000 --- a/test/nodepool_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package test - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -// Test the default variables when using the sample-input-defaults.tfvars file. -// Verify that the tfplan is using the default variables from the CONFIG-VARS -func TestNodeVMAdmin(t *testing.T) { - t.Parallel() - - variables := getDefaultPlanVars(t) - plan, err := initPlanWithVariables(t, variables) - assert.NoError(t, err) - - cluster := plan.ResourcePlannedValuesMap["module.aks.azurerm_kubernetes_cluster.aks"] - - // node_vm_admin - expectedNodeVMAdmin := "azureuser" - actualNodeVMAdmin, err := getJsonPathFromStateResource(t, cluster, "{$.linux_profile[0].admin_username}") - assert.NoError(t, err) - assert.Equal(t, expectedNodeVMAdmin, actualNodeVMAdmin, "Unexpected Node VM Admin User") - - //default_nodepool_vm_type - expectedNodepoolVMType := "Standard_E8s_v5" - actualNodepoolVMType, err := getJsonPathFromStateResource(t, cluster, "{$.default_node_pool[0].vm_size}") - assert.NoError(t, err) - assert.Equal(t, expectedNodepoolVMType, actualNodepoolVMType, "Unexpected Default Node Pool VM Type") - - //default_nodepool_os_disk_size - expectedNodepoolOSDiskSize := "128" - actualNodepoolOSDiskSize, err := getJsonPathFromStateResource(t, cluster, "{$.default_node_pool[0].os_disk_size_gb}") - assert.NoError(t, err) - assert.Equal(t, expectedNodepoolOSDiskSize, actualNodepoolOSDiskSize, "Unexpected Default Node Pool OS Disk Size") - - //default_nodepool_max_pods - expectedNodepoolMaxPods := "110" - actualNodepoolMaxPods, err := getJsonPathFromStateResource(t, cluster, "{$.default_node_pool[0].max_pods}") - assert.NoError(t, err) - assert.Equal(t, expectedNodepoolMaxPods, actualNodepoolMaxPods, "Unexpected Default Node Pool Max Pods") - - //default_nodepool_min_nodes - expectedNodepoolMinNodes := "1" - actualNodepoolMinNodes, err := getJsonPathFromStateResource(t, cluster, "{$.default_node_pool[0].min_count}") - assert.NoError(t, err) - assert.Equal(t, expectedNodepoolMinNodes, actualNodepoolMinNodes, "Unexpected Default Node Pool Min Nodes") - - //default_nodepool_max_nodes - expectedNodepoolMaxNodes := "5" - actualNodepoolMaxNodes, err := getJsonPathFromStateResource(t, cluster, "{$.default_node_pool[0].max_count}") - assert.NoError(t, err) - assert.Equal(t, expectedNodepoolMaxNodes, actualNodepoolMaxNodes, "Unexpected Default Node Pool Max Nodes") - - //default_nodepool_availability_zones - expectedNodepoolAvailability := "1" - actualNodepoolAvailability, err := getJsonPathFromStateResource(t, cluster, "{$.default_node_pool[0].zones[*]}") - assert.NoError(t, err) - assert.Equal(t, expectedNodepoolAvailability, actualNodepoolAvailability, "Unexpected Default Node Pool Zones") -} diff --git a/test/non_default_unit_test.go b/test/non_default_unit_test.go new file mode 100644 index 00000000..a3e219f0 --- /dev/null +++ b/test/non_default_unit_test.go @@ -0,0 +1,383 @@ +package test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Test the default variables when using the sample-input-defaults.tfvars file +// with storage_type set to "ha". This should engage the Azure NetApp Files module, +// with the default values as tested herein. +func TestNonDefaultAzureNetApp(t *testing.T) { + t.Parallel() + + tests := map[string]testCase{ + "accountExists": { + expected: `nil`, + resourceMapName: "module.netapp[0].azurerm_netapp_account.anf", + attributeJsonPath: "{$}", + assertFunction: assert.NotEqual, + }, + "poolExists": { + expected: `nil`, + resourceMapName: "module.netapp[0].azurerm_netapp_pool.anf", + attributeJsonPath: "{$}", + assertFunction: assert.NotEqual, + }, + "poolServiceLevel": { + expected: `Premium`, + resourceMapName: "module.netapp[0].azurerm_netapp_pool.anf", + attributeJsonPath: "{$.service_level}", + }, + "poolSize": { + expected: `4`, + resourceMapName: "module.netapp[0].azurerm_netapp_pool.anf", + attributeJsonPath: "{$.size_in_tb}", + }, + "volumeExists": { + expected: `nil`, + resourceMapName: "module.netapp[0].azurerm_netapp_volume.anf", + attributeJsonPath: "{$}", + assertFunction: assert.NotEqual, + }, + "volumeProtocols": { + expected: `["NFSv4.1"]`, + resourceMapName: "module.netapp[0].azurerm_netapp_volume.anf", + attributeJsonPath: "{$.protocols}", + }, + "volumeServiceLevel": { + expected: `Premium`, + resourceMapName: "module.netapp[0].azurerm_netapp_volume.anf", + attributeJsonPath: "{$.service_level}", + }, + "volumePath": { + expected: `export`, + resourceMapName: "module.netapp[0].azurerm_netapp_volume.anf", + attributeJsonPath: "{$.volume_path}", + assertFunction: assert.Contains, + }, + "volumeNetworkFeatures": { + expected: `Basic`, + resourceMapName: "module.netapp[0].azurerm_netapp_volume.anf", + attributeJsonPath: "{$.network_features}", + }, + "subnetExists": { + expected: `nil`, + resourceMapName: "module.vnet.azurerm_subnet.subnet[\"netapp\"]", + attributeJsonPath: "{$}", + assertFunction: assert.NotEqual, + }, + } + + // Prepare to generate the plan + varsFilePath := "../examples/sample-input-defaults.tfvars" + variables := getPlanVars(t, varsFilePath) + variables["storage_type"] = "ha" + + // Generate the plan + plan, err := initPlanWithVariables(t, variables) + require.NotNil(t, plan) + require.NoError(t, err) + + // Run the tests + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + runTest(t, tc, plan) + }) + } +} + +// Verify ACR disabled +func TestNonDefaultPlanAcrDisabled(t *testing.T) { + t.Parallel() + + acrDisabledTests := map[string]testCase{ + "acrDisabledTest": { + expected: `nil`, + resourceMapName: "azurerm_container_registry.acr[0]", + attributeJsonPath: "{$}", + message: "Azure Container Registry (ACR) present when it should not be", + }, + } + + variables := getDefaultPlanVars(t) + variables["create_container_registry"] = false + variables["container_registry_admin_enabled"] = true + plan, err := initPlanWithVariables(t, variables) + require.NotNil(t, plan) + require.NoError(t, err) + + for name, tc := range acrDisabledTests { + t.Run(name, func(t *testing.T) { + runTest(t, tc, plan) + }) + } +} + +// Verify ACR standard +func TestNonDefaultPlanACRStandard(t *testing.T) { + t.Parallel() + + acrStandardTests := map[string]testCase{ + "acrGeoRepsNotExistTest": { + expected: "[]", + resourceMapName: "azurerm_container_registry.acr[0]", + attributeJsonPath: "{$.georeplications}", + message: "Geo-replications found when they should not be present", + }, + "nameTest": { + resourceMapName: "azurerm_container_registry.acr[0]", + attributeJsonPath: "{$.name}", + assertFunction: assert.Contains, + message: "ACR name does not contain 'acr'", + }, + "skuTest": { + expected: "Standard", + resourceMapName: "azurerm_container_registry.acr[0]", + attributeJsonPath: "{$.sku}", + message: "Unexpected ACR SKU value", + }, + "adminEnabledTest": { + expected: "true", + resourceMapName: "azurerm_container_registry.acr[0]", + attributeJsonPath: "{$.admin_enabled}", + message: "Unexpected ACR admin_enabled value", + }, + } + + variables := getDefaultPlanVars(t) + variables["create_container_registry"] = true + variables["container_registry_admin_enabled"] = true + variables["container_registry_sku"] = "Standard" + plan, err := initPlanWithVariables(t, variables) + require.NotNil(t, plan) + require.NoError(t, err) + + resource, resourceExists := plan.ResourcePlannedValuesMap["azurerm_container_registry.acr[0]"] + require.True(t, resourceExists) + acrName, nameExists := resource.AttributeValues["name"].(string) + require.True(t, nameExists) + nameTestCase := acrStandardTests["nameTest"] + nameTestCase.expected = acrName + acrStandardTests["nameTest"] = nameTestCase + + for name, tc := range acrStandardTests { + t.Run(name, func(t *testing.T) { + runTest(t, tc, plan) + }) + } +} + +// Verify ACR premium +func TestNonDefaultPlanACRPremium(t *testing.T) { + t.Parallel() + + acrPremiumTests := map[string]testCase{ + "locationsTest": { + expected: "southeastus3 southeastus5", + resourceMapName: "azurerm_container_registry.acr[0]", + attributeJsonPath: "{$.georeplications[*].location}", + message: "Geo-replications do not match expected values", + }, + "nameTest": { + resourceMapName: "azurerm_container_registry.acr[0]", + attributeJsonPath: "{$.name}", + assertFunction: assert.Contains, + message: "ACR name does not contain 'acr'", + }, + "skuTest": { + expected: "Premium", + resourceMapName: "azurerm_container_registry.acr[0]", + attributeJsonPath: "{$.sku}", + message: "Unexpected ACR SKU value", + }, + "adminEnabledTest": { + expected: "true", + resourceMapName: "azurerm_container_registry.acr[0]", + attributeJsonPath: "{$.admin_enabled}", + message: "Unexpected ACR admin_enabled value", + }, + } + + variables := getDefaultPlanVars(t) + variables["create_container_registry"] = true + variables["container_registry_admin_enabled"] = true + variables["container_registry_sku"] = "Premium" + variables["container_registry_geo_replica_locs"] = []string{"southeastus5", "southeastus3"} + plan, err := initPlanWithVariables(t, variables) + require.NotNil(t, plan) + require.NoError(t, err) + + resource, resourceExists := plan.ResourcePlannedValuesMap["azurerm_container_registry.acr[0]"] + require.True(t, resourceExists) + acrName, nameExists := resource.AttributeValues["name"].(string) + require.True(t, nameExists) + nameTestCase := acrPremiumTests["nameTest"] + nameTestCase.expected = acrName + acrPremiumTests["nameTest"] = nameTestCase + + for name, tc := range acrPremiumTests { + t.Run(name, func(t *testing.T) { + runTest(t, tc, plan) + }) + } +} + +func TestNonDefaultPostgresServers(t *testing.T) { + t.Parallel() + + const DefaultPostgresServerName = "default" + + postgresResourceMapName := "module.flex_postgresql[\"" + DefaultPostgresServerName + "\"].azurerm_postgresql_flexible_server.flexpsql" + tests := map[string]testCase{ + "postgresFlexServerExists": { + expected: `nil`, + resourceMapName: postgresResourceMapName, + attributeJsonPath: "{$}", + assertFunction: assert.NotEqual, + }, + "postgresFlexServerSKUName": { + expected: `GP_Standard_D4s_v3`, + resourceMapName: postgresResourceMapName, + attributeJsonPath: "{$.sku_name}", + }, + "postgresFlexServerStorageSize": { + expected: `131072`, + resourceMapName: postgresResourceMapName, + attributeJsonPath: "{$.storage_mb}", + }, + "postgresFlexServerBackupRetentionDays": { + expected: `7`, + resourceMapName: postgresResourceMapName, + attributeJsonPath: "{$.backup_retention_days}", + }, + "postgresFlexServerGeoRedundantBackup": { + expected: `false`, + resourceMapName: postgresResourceMapName, + attributeJsonPath: "{$.geo_redundant_backup_enabled}", + }, + "postgresFlexServerAdminLogin": { + expected: `pgadmin`, + resourceMapName: postgresResourceMapName, + attributeJsonPath: "{$.administrator_login}", + }, + "postgresFlexServerAdminPassword": { + expected: `my$up3rS3cretPassw0rd`, + resourceMapName: postgresResourceMapName, + attributeJsonPath: "{$.administrator_password}", + }, + "postgresFlexServerVersion": { + expected: `15`, + resourceMapName: postgresResourceMapName, + attributeJsonPath: "{$.version}", + }, + "postgresFlexServerSSLEnforcement": { + expected: `OFF`, + resourceMapName: postgresResourceMapName, + attributeJsonPath: "{$.postgresql_configurations[*].require_secure_transport}", + assertFunction: assert.NotEqual, + }, + "postgresFlexServerVnetId": { + expected: ``, + resourceMapName: postgresResourceMapName, + attributeJsonPath: "{$.virtual_network_id}", + }, + "postgresFlexServerConfigurationMaxPreparedTransactionsName": { + expected: `max_prepared_transactions`, + resourceMapName: "module.flex_postgresql[\"" + DefaultPostgresServerName + "\"].azurerm_postgresql_flexible_server_configuration.flexpsql[\"max_prepared_transactions\"]", + attributeJsonPath: "{$.name}", + }, + "postgresFlexServerConfigurationMaxPreparedTransactionsValue": { + expected: `1024`, + resourceMapName: "module.flex_postgresql[\"" + DefaultPostgresServerName + "\"].azurerm_postgresql_flexible_server_configuration.flexpsql[\"max_prepared_transactions\"]", + attributeJsonPath: "{$.value}", + }, + } + + // Prepare to generate the plan + variables := getDefaultPlanVars(t) + variables["postgres_servers"] = map[string]any{ + DefaultPostgresServerName: map[string]any{}, + } + + // Generate the plan + plan, err := initPlanWithVariables(t, variables) + require.NotNil(t, plan) + require.NoError(t, err) + + // Run the tests + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + runTest(t, tc, plan) + }) + } +} + +func TestNonDefaultRbacEnabledGroupIds(t *testing.T) { + t.Parallel() + + const TENANT_ID = "2492e7f7-df5d-4f17-95dc-63528774e820" + + var ADMIN_IDS = []string{ + "59218b02-7421-4e2d-840a-37ce0d676afa", + "498afef2-ef42-4099-88f2-4138976df67f", + } + + tests := map[string]testCase{ + "aadRbacExists": { + expected: `nil`, + resourceMapName: "module.aks.azurerm_kubernetes_cluster.aks", + attributeJsonPath: "{$.azure_active_directory_role_based_access_control}", + assertFunction: assert.NotEqual, + }, + "aadRbacTenant": { + expected: TENANT_ID, + resourceMapName: "module.aks.azurerm_kubernetes_cluster.aks", + attributeJsonPath: "{$.azure_active_directory_role_based_access_control[0].tenant_id}", + }, + "aadRbacAdminIDs": { + expected: `["` + ADMIN_IDS[0] + `","` + ADMIN_IDS[1] + `"]`, + resourceMapName: "module.aks.azurerm_kubernetes_cluster.aks", + attributeJsonPath: "{$.azure_active_directory_role_based_access_control[0].admin_group_object_ids}", + }, + } + + // Initialize the default variables map + variables := getDefaultPlanVars(t) + + // Set RBAC to true + variables["rbac_aad_enabled"] = true + + // rbac_aad_tenant_id is required + variables["rbac_aad_tenant_id"] = TENANT_ID + + // set the rbac_aad_admin_group_object_ids property + variables["rbac_aad_admin_group_object_ids"] = ADMIN_IDS + + // Generate the plan + plan, err := initPlanWithVariables(t, variables) + require.NotNil(t, plan) + require.NoError(t, err) + + // Run the tests + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + runTest(t, tc, plan) + }) + } +} + +func TestNonDefaultRbacEnabledNoTenant(t *testing.T) { + t.Parallel() + + // Initialize the default variables map + variables := getDefaultPlanVars(t) + + // Set RBAC to true + variables["rbac_aad_enabled"] = true + + _, err := initPlanWithVariables(t, variables) + assert.ErrorContains(t, err, "Missing required argument") +} diff --git a/test/postgres_test.go b/test/postgres_test.go deleted file mode 100644 index c1f521e5..00000000 --- a/test/postgres_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const ( - DefaultPostgresServerName = "default" -) - -// TestPostgresServers verifies all PostgreSQL Flexible Server configurations -func TestPostgresServers(t *testing.T) { - t.Parallel() - - postgresResourceMapName := "module.flex_postgresql[\"" + DefaultPostgresServerName + "\"].azurerm_postgresql_flexible_server.flexpsql" - tests := map[string]testCase{ - "postgresFlexServerExists": { - expected: `nil`, - resourceMapName: postgresResourceMapName, - attributeJsonPath: "{$}", - assertFunction: assert.NotEqual, - }, - "postgresFlexServerSKUName": { - expected: `GP_Standard_D4s_v3`, - resourceMapName: postgresResourceMapName, - attributeJsonPath: "{$.sku_name}", - }, - "postgresFlexServerStorageSize": { - expected: `131072`, - resourceMapName: postgresResourceMapName, - attributeJsonPath: "{$.storage_mb}", - }, - "postgresFlexServerBackupRetentionDays": { - expected: `7`, - resourceMapName: postgresResourceMapName, - attributeJsonPath: "{$.backup_retention_days}", - }, - "postgresFlexServerGeoRedundantBackup": { - expected: `false`, - resourceMapName: postgresResourceMapName, - attributeJsonPath: "{$.geo_redundant_backup_enabled}", - }, - "postgresFlexServerAdminLogin": { - expected: `pgadmin`, - resourceMapName: postgresResourceMapName, - attributeJsonPath: "{$.administrator_login}", - }, - "postgresFlexServerAdminPassword": { - expected: `my$up3rS3cretPassw0rd`, - resourceMapName: postgresResourceMapName, - attributeJsonPath: "{$.administrator_password}", - }, - "postgresFlexServerVersion": { - expected: `15`, - resourceMapName: postgresResourceMapName, - attributeJsonPath: "{$.version}", - }, - "postgresFlexServerSSLEnforcement": { - expected: `OFF`, - resourceMapName: postgresResourceMapName, - attributeJsonPath: "{$.postgresql_configurations[*].require_secure_transport}", - assertFunction: assert.NotEqual, - }, - "postgresFlexServerVnetId": { - expected: ``, - resourceMapName: postgresResourceMapName, - attributeJsonPath: "{$.virtual_network_id}", - }, - "postgresFlexServerConfigurationMaxPreparedTransactionsName": { - expected: `max_prepared_transactions`, - resourceMapName: "module.flex_postgresql[\"" + DefaultPostgresServerName + "\"].azurerm_postgresql_flexible_server_configuration.flexpsql[\"max_prepared_transactions\"]", - attributeJsonPath: "{$.name}", - }, - "postgresFlexServerConfigurationMaxPreparedTransactionsValue": { - expected: `1024`, - resourceMapName: "module.flex_postgresql[\"" + DefaultPostgresServerName + "\"].azurerm_postgresql_flexible_server_configuration.flexpsql[\"max_prepared_transactions\"]", - attributeJsonPath: "{$.value}", - }, - } - - // Prepare to generate the plan - variables := getDefaultPlanVars(t) - variables["postgres_servers"] = map[string]any{ - DefaultPostgresServerName: map[string]any{}, - } - - // Generate the plan - plan, err := initPlanWithVariables(t, variables) - require.NotNil(t, plan) - require.NoError(t, err) - - // Run the tests - for name, tc := range tests { - t.Run(name, func(t *testing.T) { - runTest(t, tc, plan) - }) - } -} diff --git a/test/rbac_test.go b/test/rbac_test.go deleted file mode 100644 index cbcd10d7..00000000 --- a/test/rbac_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const ( - RBAC_STATEFUL_SOURCE = "module.aks.azurerm_kubernetes_cluster.aks" - TENANT_ID = "2492e7f7-df5d-4f17-95dc-63528774e820" -) - -var ADMIN_IDS = []string{ - "59218b02-7421-4e2d-840a-37ce0d676afa", - "498afef2-ef42-4099-88f2-4138976df67f", -} - -func TestDefaultRbacEnabledGroupIds(t *testing.T) { - tests := map[string]testCase{ - "aadRbacExists": { - expected: `nil`, - resourceMapName: "module.aks.azurerm_kubernetes_cluster.aks", - attributeJsonPath: "{$.azure_active_directory_role_based_access_control}", - assertFunction: assert.NotEqual, - }, - "aadRbacTenant": { - expected: TENANT_ID, - resourceMapName: "module.aks.azurerm_kubernetes_cluster.aks", - attributeJsonPath: "{$.azure_active_directory_role_based_access_control[0].tenant_id}", - }, - "aadRbacAdminIDs": { - expected: `["` + ADMIN_IDS[0] + `","` + ADMIN_IDS[1] + `"]`, - resourceMapName: "module.aks.azurerm_kubernetes_cluster.aks", - attributeJsonPath: "{$.azure_active_directory_role_based_access_control[0].admin_group_object_ids}", - }, - } - - // Initialize the default variables map - variables := getDefaultPlanVars(t) - - // Set RBAC to true - variables["rbac_aad_enabled"] = true - - // rbac_aad_tenant_id is required - variables["rbac_aad_tenant_id"] = TENANT_ID - - // set the rbac_aad_admin_group_object_ids property - variables["rbac_aad_admin_group_object_ids"] = ADMIN_IDS - - // Generate the plan - plan, err := initPlanWithVariables(t, variables) - require.NotNil(t, plan) - require.NoError(t, err) - - // Run the tests - for name, tc := range tests { - t.Run(name, func(t *testing.T) { - runTest(t, tc, plan) - }) - } -} - -func TestDefaultRbacEnabledNoTenant(t *testing.T) { - t.Parallel() - - // Initialize the default variables map - variables := getDefaultPlanVars(t) - - // Set RBAC to true - variables["rbac_aad_enabled"] = true - - _, err := initPlanWithVariables(t, variables) - assert.ErrorContains(t, err, "Missing required argument") -}