@@ -34,6 +34,8 @@ import (
3434 "github.com/otiai10/copy"
3535)
3636
37+ var testRegex = regexp .MustCompile ("func (TestAcc[^(]+)" )
38+
3739// TerraformGoogleConversionNext is for both tfplan2cai and cai2hcl conversions
3840// and copying other files, such as transport.go
3941type TerraformGoogleConversionNext struct {
@@ -105,6 +107,11 @@ func (tgc TerraformGoogleConversionNext) GenerateObject(object api.Resource, out
105107 if ! object .IsExcluded () {
106108 tgc .GenerateResource (object , * templateData , outputFolder , generateCode , generateDocs )
107109 tgc .addTestsFromSamples (& object )
110+ if object .TGCIncludeHandwrittenTests {
111+ if err := tgc .addTestsFromHandwrittenTests (& object ); err != nil {
112+ log .Printf ("Error adding examples from handwritten tests: %v" , err )
113+ }
114+ }
108115 tgc .GenerateResourceTests (object , * templateData , outputFolder )
109116 }
110117}
@@ -340,6 +347,53 @@ func (tgc TerraformGoogleConversionNext) addTestsFromSamples(object *api.Resourc
340347 })
341348 }
342349}
350+ func (tgc TerraformGoogleConversionNext ) addTestsFromHandwrittenTests (object * api.Resource ) error {
351+ if object .ProductMetadata == nil {
352+ return nil
353+ }
354+ product := object .ProductMetadata
355+ productName := google .Underscore (product .Name )
356+ resourceFullName := fmt .Sprintf ("%s_%s" , productName , google .Underscore (object .Name ))
357+ handwrittenTestFilePath := fmt .Sprintf ("third_party/terraform/services/%s/resource_%s_test.go" , productName , resourceFullName )
358+ data , err := os .ReadFile (handwrittenTestFilePath )
359+ for err != nil {
360+ if errors .Is (err , os .ErrNotExist ) {
361+ if strings .HasSuffix (handwrittenTestFilePath , ".tmpl" ) {
362+ log .Printf ("no handwritten test file found for %s" , resourceFullName )
363+ return nil
364+ }
365+ handwrittenTestFilePath += ".tmpl"
366+ data , err = os .ReadFile (handwrittenTestFilePath )
367+ } else {
368+ return fmt .Errorf ("error reading handwritten test file %s: %v" , handwrittenTestFilePath , err )
369+ }
370+ }
371+
372+ // Skip adding handwritten tests that are already defined in yaml (because they have custom overrides etc.)
373+ testNamesInYAML := make (map [string ]struct {})
374+ for _ , test := range object .TGCTests {
375+ if test .Name != "" {
376+ testNamesInYAML [test .Name ] = struct {}{}
377+ }
378+ }
379+
380+ matches := testRegex .FindAllSubmatch (data , - 1 )
381+ tests := make ([]resource.TGCTest , len (matches ))
382+ for i , match := range matches {
383+ if len (match ) == 2 {
384+ if _ , ok := testNamesInYAML [string (match [1 ])]; ok {
385+ continue
386+ }
387+ tests [i ] = resource.TGCTest {
388+ Name : string (match [1 ]),
389+ }
390+ }
391+ }
392+
393+ object .TGCTests = append (object .TGCTests , tests ... )
394+
395+ return nil
396+ }
343397
344398// Generates the list of resources, and gets the count of resources.
345399// The resource object has the format
0 commit comments