|
| 1 | +package test |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/gruntwork-io/terratest/modules/k8s" |
| 5 | + "github.com/gruntwork-io/terratest/modules/logger" |
| 6 | + "github.com/gruntwork-io/terratest/modules/terraform" |
| 7 | + "github.com/stretchr/testify/assert" |
| 8 | + "io/ioutil" |
| 9 | + "path/filepath" |
| 10 | + "testing" |
| 11 | +) |
| 12 | + |
| 13 | +// This approach compares the entire plan json output to a static json file in the test directory. |
| 14 | +// The file needs to be updated as the configuration changes to pass the test. An improvement would |
| 15 | +// be to get targeted plan output for specific resources and use jsonpath to test those resources |
| 16 | +// exist in the plan. |
| 17 | +func TestKubeAdmClusterConfig(t *testing.T) { |
| 18 | + t.Parallel() |
| 19 | + |
| 20 | + planFilePath := filepath.Join(".", "plan.out") |
| 21 | + |
| 22 | + terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{ |
| 23 | + // The path to where our Terraform code is located |
| 24 | + TerraformDir: "..", |
| 25 | + PlanFilePath: planFilePath, |
| 26 | + |
| 27 | + // Variables to pass to our Terraform code using -var-file options |
| 28 | + VarFiles: []string{"test_terraform.tfvars"}, |
| 29 | + |
| 30 | + // Disable colors in Terraform commands so its easier to parse stdout/stderr |
| 31 | + NoColor: true, |
| 32 | + // Disable logging |
| 33 | + Logger: logger.New(logger.Discard), |
| 34 | + }) |
| 35 | + |
| 36 | + // At the end of the test, run `terraform destroy` to clean up any resources that were created. |
| 37 | + defer terraform.Destroy(t, terraformOptions) |
| 38 | + |
| 39 | + // This will run `terraform init` and `terraform apply` and `terraform show` and return the plan |
| 40 | + // json at `PlanFilePath` and fail the test if there are any errors. |
| 41 | + planJson := terraform.InitAndPlanAndShow(t, terraformOptions) |
| 42 | + |
| 43 | + // Use jsonpath to extract the expected json nodes on the instance from the plan. You can alternatively |
| 44 | + // use https://github.com/hashicorp/terraform-json to get a concrete struct with all the types resolved. |
| 45 | + var actualConfig []map[string]interface{} |
| 46 | + var expectedConfig []map[string]interface{} |
| 47 | + |
| 48 | + k8s.UnmarshalJSONPath( |
| 49 | + t, |
| 50 | + []byte(planJson), |
| 51 | + "{ }", |
| 52 | + &actualConfig, |
| 53 | + ) |
| 54 | + |
| 55 | + expectedBuf, _ := ioutil.ReadFile(filepath.Join(".", "plan_config.json")) |
| 56 | + |
| 57 | + k8s.UnmarshalJSONPath( |
| 58 | + t, |
| 59 | + expectedBuf, |
| 60 | + "{ }", |
| 61 | + &expectedConfig, |
| 62 | + ) |
| 63 | + |
| 64 | + assert.Equal(t, expectedConfig, actualConfig) |
| 65 | + |
| 66 | +} |
0 commit comments