github.com/fortexxx/gqlgen@v0.10.3-0.20191216030626-ca5ea8b21ead/codegen/templates/import_test.go (about)

     1  package templates
     2  
     3  import (
     4  	"go/types"
     5  	"os"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/require"
     9  )
    10  
    11  func TestImports(t *testing.T) {
    12  	wd, err := os.Getwd()
    13  	require.NoError(t, err)
    14  
    15  	aBar := "github.com/99designs/gqlgen/codegen/templates/testdata/a/bar"
    16  	bBar := "github.com/99designs/gqlgen/codegen/templates/testdata/b/bar"
    17  	mismatch := "github.com/99designs/gqlgen/codegen/templates/testdata/pkg_mismatch"
    18  
    19  	t.Run("multiple lookups is ok", func(t *testing.T) {
    20  		a := Imports{destDir: wd}
    21  
    22  		require.Equal(t, "bar", a.Lookup(aBar))
    23  		require.Equal(t, "bar", a.Lookup(aBar))
    24  	})
    25  
    26  	t.Run("lookup by type", func(t *testing.T) {
    27  		a := Imports{destDir: wd}
    28  
    29  		pkg := types.NewPackage("github.com/99designs/gqlgen/codegen/templates/testdata/b/bar", "bar")
    30  		typ := types.NewNamed(types.NewTypeName(0, pkg, "Boolean", types.Typ[types.Bool]), types.Typ[types.Bool], nil)
    31  
    32  		require.Equal(t, "bar.Boolean", a.LookupType(typ))
    33  	})
    34  
    35  	t.Run("duplicates are decollisioned", func(t *testing.T) {
    36  		a := Imports{destDir: wd}
    37  
    38  		require.Equal(t, "bar", a.Lookup(aBar))
    39  		require.Equal(t, "bar1", a.Lookup(bBar))
    40  
    41  		t.Run("additionial calls get decollisioned name", func(t *testing.T) {
    42  			require.Equal(t, "bar1", a.Lookup(bBar))
    43  		})
    44  	})
    45  
    46  	t.Run("package name defined in code will be used", func(t *testing.T) {
    47  		a := Imports{destDir: wd}
    48  
    49  		require.Equal(t, "turtles", a.Lookup(mismatch))
    50  	})
    51  
    52  	t.Run("string printing for import block", func(t *testing.T) {
    53  		a := Imports{destDir: wd}
    54  		a.Lookup(aBar)
    55  		a.Lookup(bBar)
    56  		a.Lookup(mismatch)
    57  
    58  		require.Equal(
    59  			t,
    60  			`"github.com/99designs/gqlgen/codegen/templates/testdata/a/bar"
    61  bar1 "github.com/99designs/gqlgen/codegen/templates/testdata/b/bar"
    62  turtles "github.com/99designs/gqlgen/codegen/templates/testdata/pkg_mismatch"`,
    63  			a.String(),
    64  		)
    65  	})
    66  
    67  	t.Run("aliased imports will not collide", func(t *testing.T) {
    68  		a := Imports{destDir: wd}
    69  
    70  		_, _ = a.Reserve(aBar, "abar")
    71  		_, _ = a.Reserve(bBar, "bbar")
    72  
    73  		require.Equal(t, `abar "github.com/99designs/gqlgen/codegen/templates/testdata/a/bar"
    74  bbar "github.com/99designs/gqlgen/codegen/templates/testdata/b/bar"`, a.String())
    75  	})
    76  
    77  }