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