github.com/blend/go-sdk@v1.20220411.3/sourceutil/copy_rewriter_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package sourceutil
     9  
    10  import (
    11  	"bytes"
    12  	"context"
    13  	"strings"
    14  	"testing"
    15  
    16  	"github.com/blend/go-sdk/ref"
    17  )
    18  
    19  func Test_CopyRewrite_rewriteGoAst(t *testing.T) {
    20  	t.Parallel()
    21  
    22  	file := `package foo
    23  
    24  import "fmt"
    25  import "foo/bar"
    26  import foo "bar/foo"
    27  import "sdk/httpmetrics"
    28  
    29  func main() {
    30  	fmt.Println(bar.Foo)
    31  	println(foo.Bar)
    32  }
    33  `
    34  
    35  	expected := `package foo
    36  
    37  import "fmt"
    38  import "golang.org/foo/bar"
    39  import foo "golang.org/bar/foo"
    40  import httpmetrics "golang.org/sdk/stats/httpmetrics"
    41  
    42  func main() {
    43  	fmt.Printf(bar.Foo)
    44  	println(foo.Bar)
    45  }
    46  `
    47  
    48  	ctx := context.Background()
    49  	cr := CopyRewriter{
    50  		GoImportVisitors: []GoImportVisitor{
    51  			GoImportRewritePrefix("foo", "golang.org/foo"),
    52  			GoImportRewritePrefix("bar", "golang.org/bar"),
    53  			GoImportRewrite(
    54  				OptGoImportPathMatches("^sdk/httpmetrics"),
    55  				OptGoImportAddName("httpmetrics"),
    56  				OptGoImportSetPath("golang.org/sdk/stats/httpmetrics"),
    57  			),
    58  		},
    59  		GoAstVistiors: []GoAstVisitor{
    60  			GoAstRewrite(
    61  				GoIsPackageCall("fmt", "Println"),
    62  				GoRewritePackageCall("fmt", "Printf"),
    63  			),
    64  		},
    65  		Debug: ref.Bool(true),
    66  	}
    67  	var buf bytes.Buffer
    68  	if err := cr.rewriteGoAst(ctx, "main.go", []byte(file), &buf); err != nil {
    69  		t.Error(err)
    70  		t.FailNow()
    71  	}
    72  	if buf.String() == "" {
    73  		t.Errorf("buffer was empty")
    74  		t.FailNow()
    75  	}
    76  
    77  	if !strings.HasPrefix(buf.String(), expected) {
    78  		t.Logf(buf.String())
    79  		t.Errorf("invalid output")
    80  		t.FailNow()
    81  	}
    82  }