Skip to content

Commit

Permalink
go rewrite - Finish test template (GoogleCloudPlatform#10468)
Browse files Browse the repository at this point in the history
  • Loading branch information
c2thorn authored and BBBmau committed May 8, 2024
1 parent e41c825 commit 20648c4
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 7 deletions.
45 changes: 43 additions & 2 deletions mmv1/api/resource/examples.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"fmt"
"net/url"
"path/filepath"
"strings"
"text/template"

"github.com/GoogleCloudPlatform/magic-modules/mmv1/google"
Expand Down Expand Up @@ -157,7 +158,8 @@ type Examples struct {
// your test so avoid if you can.
PullExternal bool `yaml:"pull_external"`

HCLText string
DocumentationHCLText string
TestHCLText string
}

func (e *Examples) UnmarshalYAML(n *yaml.Node) error {
Expand All @@ -175,7 +177,40 @@ func (e *Examples) UnmarshalYAML(n *yaml.Node) error {
return nil
}

// Executes example templates for documentation and tests
func (e *Examples) SetHCLText() {
e.DocumentationHCLText = ExecuteHCL(e)

copy := e
// Override vars to inject test values into configs - will have
// - "a-example-var-value%{random_suffix}""
// - "%{my_var}" for overrides that have custom Golang values
for key, value := range copy.Vars {
var newVal string
if strings.Contains(value, "-") {
newVal = fmt.Sprintf("tf-test-%s", value)
} else if strings.Contains(value, "_") {
newVal = fmt.Sprintf("tf_test_%s", value)
} else {
// Some vars like descriptions shouldn't have prefix
newVal = value
}
// Random suffix is 10 characters and standard name length <= 64
if len(newVal) > 54 {
newVal = newVal[:54]
}
copy.Vars[key] = fmt.Sprintf("%s%%{random_suffix}", newVal)
}

// Apply overrides from YAML
for key := range copy.TestVarsOverrides {
copy.Vars[key] = fmt.Sprintf("%%{%s}", key)
}

e.TestHCLText = ExecuteHCL(copy)
}

func ExecuteHCL(e *Examples) string {
templatePath := e.ConfigPath
templates := []string{
templatePath,
Expand All @@ -192,7 +227,13 @@ func (e *Examples) SetHCLText() {
glog.Exit(err)
}

e.HCLText = contents.String()
rs := contents.String()

if !strings.HasSuffix(rs, "\n") {
rs = fmt.Sprintf("%s\n", rs)
}

return rs
}

// func (e *Examples) config_documentation(pwd) {
Expand Down
57 changes: 53 additions & 4 deletions mmv1/templates/terraform/examples/base_configs/test_file.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func TestAcc{{ $e.TestSlug $.Res.ProductMetadata.Name $.Res.Name }}(t *testing.T
{{- end }}
t.Parallel()

context := map[string]interface{} {
context := map[string]interface{}{
{{- range $varKey, $varVal := $e.TestEnvVars }}
{{- if eq $varVal $.ORGID }}
"{{$varKey}}": envvar.GetTestOrgFromEnv(t),
Expand Down Expand Up @@ -119,10 +119,59 @@ func TestAcc{{ $e.TestSlug $.Res.ProductMetadata.Name $.Res.Name }}(t *testing.T

func testAcc{{ $e.TestSlug $.Res.ProductMetadata.Name $.Res.Name }}(context map[string]interface{}) string {
return acctest.Nprintf(`
{{ $e.HCLText }}
{{ $e.TestHCLText -}}
`, context)
}

{{- end }}
{{ end }}

{{ if not $.Res.SkipDelete }}
func testAccCheck{{ $.Res.ResourceName }}DestroyProducer(t *testing.T) func(s *terraform.State) error {
return func(s *terraform.State) error {
for name, rs := range s.RootModule().Resources {
if rs.Type != "{{ $.Res.TerraformName }}" {
continue
}
if strings.HasPrefix(name, "data.") {
continue
}
{{- if $.Res.CustomCode.TestCheckDestroy }}
{{/*TODO Q2: Custom template for TestCheckDestroy */}}
{{- else }}

config := acctest.GoogleProviderConfig(t)

url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{"{{"}}{{$.Res.ProductMetadata.Name}}{{"BasePath}}"}}{{$.Res.SelfLinkUri}}")
if err != nil {
return err
}

billingProject := ""

if config.BillingProject != "" {
billingProject = config.BillingProject
}

{{/*TODO Q2: Destroy Producer */}}
_, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "{{ camelize $.Res.ReadVerb "upper" }}",
Project: billingProject,
RawURL: url,
UserAgent: config.UserAgent,
{{- if $.Res.ErrorRetryPredicates }}
ErrorRetryPredicates: []transport_tpg.RetryErrorPredicateFunc{ {{- join $.Res.ErrorRetryPredicates "," -}} },
{{- end }}
{{- if $.Res.ErrorAbortPredicates }}
ErrorAbortPredicates: []transport_tpg.RetryErrorPredicateFunc{ {{- join $.Res.ErrorAbortPredicates "," -}} },
{{- end }}
})
if err == nil {
return fmt.Errorf("{{ $.Res.ResourceName }} still exists at %s", url)
}
{{- end }}
}

return nil
}
}
{{- end }}
2 changes: 1 addition & 1 deletion mmv1/templates/terraform/resource.html.markdown.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ values will be stored in the raw state as plain text: {{ $.SensitivePropsToStrin


```hcl
{{ $e.HCLText }}
{{ $e.DocumentationHCLText -}}
```
{{- end }}
{{- end }}
Expand Down

0 comments on commit 20648c4

Please sign in to comment.