-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
gen_test.go
418 lines (367 loc) 路 11.2 KB
/
gen_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package gen
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"regexp"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/pkg/v3/codegen/testing/test"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/executable"
)
func TestInputUsage(t *testing.T) {
t.Parallel()
pkg := &pkgContext{}
arrayUsage := pkg.getInputUsage("FooArray")
assert.Equal(
t,
"FooArrayInput is an input type that accepts FooArray and FooArrayOutput values.\nYou can construct a "+
"concrete instance of `FooArrayInput` via:\n\n\t\t FooArray{ FooArgs{...} }\n ",
arrayUsage)
mapUsage := pkg.getInputUsage("FooMap")
assert.Equal(
t,
"FooMapInput is an input type that accepts FooMap and FooMapOutput values.\nYou can construct a concrete"+
" instance of `FooMapInput` via:\n\n\t\t FooMap{ \"key\": FooArgs{...} }\n ",
mapUsage)
ptrUsage := pkg.getInputUsage("FooPtr")
assert.Equal(
t,
"FooPtrInput is an input type that accepts FooArgs, FooPtr and FooPtrOutput values.\nYou can construct a "+
"concrete instance of `FooPtrInput` via:\n\n\t\t FooArgs{...}\n\n or:\n\n\t\t nil\n ",
ptrUsage)
usage := pkg.getInputUsage("Foo")
assert.Equal(
t,
"FooInput is an input type that accepts FooArgs and FooOutput values.\nYou can construct a concrete instance"+
" of `FooInput` via:\n\n\t\t FooArgs{...}\n ",
usage)
}
func TestGoPackageName(t *testing.T) {
t.Parallel()
assert.Equal(t, "aws", goPackage("aws"))
assert.Equal(t, "azurenextgen", goPackage("azure-nextgen"))
assert.Equal(t, "plantprovider", goPackage("plant-provider"))
assert.Equal(t, "", goPackage(""))
}
func TestGeneratePackage(t *testing.T) {
t.Parallel()
generatePackage := func(tool string, pkg *schema.Package, files map[string][]byte) (map[string][]byte, error) {
for f := range files {
t.Logf("Ignoring extraFile %s", f)
}
return GeneratePackage(tool, pkg)
}
test.TestSDKCodegen(t, &test.SDKCodegenOptions{
Language: "go",
GenPackage: generatePackage,
Checks: map[string]test.CodegenCheck{
"go/compile": typeCheckGeneratedPackage,
"go/test": testGeneratedPackage,
},
TestCases: test.PulumiPulumiSDKTests,
})
}
func inferModuleName(codeDir string) string {
// For example for this path:
//
// codeDir = "../testing/test/testdata/external-resource-schema/go/"
//
// We will generate "$codeDir/go.mod" using
// `external-resource-schema` as the module name so that it
// can compile independently.
return filepath.Base(filepath.Dir(codeDir))
}
func typeCheckGeneratedPackage(t *testing.T, codeDir string) {
sdk, err := filepath.Abs(filepath.Join("..", "..", "..", "sdk"))
require.NoError(t, err)
goExe, err := executable.FindExecutable("go")
require.NoError(t, err)
goMod := filepath.Join(codeDir, "go.mod")
alreadyHaveGoMod, err := test.PathExists(goMod)
require.NoError(t, err)
if alreadyHaveGoMod {
t.Logf("Found an existing go.mod, leaving as is")
} else {
test.RunCommand(t, "go_mod_init", codeDir, goExe, "mod", "init", inferModuleName(codeDir))
replacement := fmt.Sprintf("github.com/pulumi/pulumi/sdk/v3=%s", sdk)
test.RunCommand(t, "go_mod_edit", codeDir, goExe, "mod", "edit", "-replace", replacement)
}
test.RunCommand(t, "go_mod_tidy", codeDir, goExe, "mod", "tidy")
test.RunCommand(t, "go_build", codeDir, goExe, "build", "-v", "all")
}
func testGeneratedPackage(t *testing.T, codeDir string) {
goExe, err := executable.FindExecutable("go")
require.NoError(t, err)
test.RunCommand(t, "go-test", codeDir, goExe, "test", fmt.Sprintf("%s/...", inferModuleName(codeDir)))
}
func TestGenerateTypeNames(t *testing.T) {
t.Parallel()
test.TestTypeNameCodegen(t, "go", func(pkg *schema.Package) test.TypeNameGeneratorFunc {
err := pkg.ImportLanguages(map[string]schema.Language{"go": Importer})
require.NoError(t, err)
var goPkgInfo GoPackageInfo
if goInfo, ok := pkg.Language["go"].(GoPackageInfo); ok {
goPkgInfo = goInfo
}
packages := generatePackageContextMap("test", pkg, goPkgInfo, nil)
root, ok := packages[""]
require.True(t, ok)
return func(t schema.Type) string {
return root.typeString(t)
}
})
}
func readSchemaFile(file string) *schema.Package {
// Read in, decode, and import the schema.
schemaBytes, err := ioutil.ReadFile(filepath.Join("..", "testing", "test", "testdata", file))
if err != nil {
panic(err)
}
var pkgSpec schema.PackageSpec
if err = json.Unmarshal(schemaBytes, &pkgSpec); err != nil {
panic(err)
}
pkg, err := schema.ImportSpec(pkgSpec, map[string]schema.Language{"go": Importer})
if err != nil {
panic(err)
}
return pkg
}
// We test the naming/module structure of generated packages.
func TestPackageNaming(t *testing.T) {
t.Parallel()
testCases := []struct {
importBasePath string
rootPackageName string
name string
expectedRoot string
}{
{
importBasePath: "github.com/pulumi/pulumi-azure-quickstart-acr-geo-replication/sdk/go/acr",
expectedRoot: "acr",
},
{
importBasePath: "github.com/ihave/animport",
rootPackageName: "root",
expectedRoot: "",
},
{
name: "named-package",
expectedRoot: "namedpackage",
},
}
for _, tt := range testCases {
tt := tt
t.Run(tt.expectedRoot, func(t *testing.T) {
t.Parallel()
// This schema is arbitrary. We just needed a filled out schema. All
// path decisions should be made based off of the Name and
// Language[go] fields (which we set after import).
schema := readSchemaFile(filepath.Join("schema", "good-enum-1.json"))
if tt.name != "" {
// We want there to be a name, so if one isn't provided we
// default to the schema.
schema.Name = tt.name
}
schema.Language = map[string]interface{}{
"go": GoPackageInfo{
ImportBasePath: tt.importBasePath,
RootPackageName: tt.rootPackageName,
},
}
files, err := GeneratePackage("test", schema)
require.NoError(t, err)
ordering := make([]string, len(files))
var i int
for k := range files {
ordering[i] = k
i++
}
ordering = sort.StringSlice(ordering)
require.NotEmpty(t, files, "This test only works when files are generated")
for _, k := range ordering {
root := strings.Split(k, "/")[0]
if tt.expectedRoot != "" {
require.Equal(t, tt.expectedRoot, root, "Root should precede all cases. Got file %s", k)
}
// We should work on a way to assert this is one level higher then it otherwise would be.
}
})
}
}
func TestTokenToType(t *testing.T) {
t.Parallel()
const awsImportBasePath = "github.com/pulumi/pulumi-aws/sdk/v4/go/aws"
awsSpec := schema.PackageSpec{
Name: "aws",
Meta: &schema.MetadataSpec{
ModuleFormat: "(.*)(?:/[^/]*)",
},
}
const googleNativeImportBasePath = "github.com/pulumi/pulumi-google-native/sdk/go/google"
googleNativeSpec := schema.PackageSpec{
Name: "google-native",
}
tests := []struct {
pkg *pkgContext
token string
expected string
}{
{
pkg: &pkgContext{
pkg: importSpec(t, awsSpec),
importBasePath: awsImportBasePath,
},
token: "aws:s3/BucketWebsite:BucketWebsite",
expected: "s3.BucketWebsite",
},
{
pkg: &pkgContext{
pkg: importSpec(t, awsSpec),
importBasePath: awsImportBasePath,
pkgImportAliases: map[string]string{
"github.com/pulumi/pulumi-aws/sdk/v4/go/aws/s3": "awss3",
},
},
token: "aws:s3/BucketWebsite:BucketWebsite",
expected: "awss3.BucketWebsite",
},
{
pkg: &pkgContext{
pkg: importSpec(t, googleNativeSpec),
importBasePath: googleNativeImportBasePath,
pkgImportAliases: map[string]string{
"github.com/pulumi/pulumi-google-native/sdk/go/google/dns/v1": "dns",
},
},
token: "google-native:dns/v1:DnsKeySpec",
expected: "dns.DnsKeySpec",
},
}
//nolint:paralleltest // false positive because range var isn't used directly in t.Run(name) arg
for _, tt := range tests {
tt := tt
t.Run(tt.token+"=>"+tt.expected, func(t *testing.T) {
t.Parallel()
actual := tt.pkg.tokenToType(tt.token)
assert.Equal(t, tt.expected, actual)
})
}
}
func TestTokenToResource(t *testing.T) {
t.Parallel()
const awsImportBasePath = "github.com/pulumi/pulumi-aws/sdk/v4/go/aws"
awsSpec := schema.PackageSpec{
Name: "aws",
Meta: &schema.MetadataSpec{
ModuleFormat: "(.*)(?:/[^/]*)",
},
}
const googleNativeImportBasePath = "github.com/pulumi/pulumi-google-native/sdk/go/google"
googleNativeSpec := schema.PackageSpec{
Name: "google-native",
}
tests := []struct {
pkg *pkgContext
token string
expected string
}{
{
pkg: &pkgContext{
pkg: importSpec(t, awsSpec),
importBasePath: awsImportBasePath,
},
token: "aws:s3/Bucket:Bucket",
expected: "s3.Bucket",
},
{
pkg: &pkgContext{
pkg: importSpec(t, awsSpec),
importBasePath: awsImportBasePath,
pkgImportAliases: map[string]string{
"github.com/pulumi/pulumi-aws/sdk/v4/go/aws/s3": "awss3",
},
},
token: "aws:s3/Bucket:Bucket",
expected: "awss3.Bucket",
},
{
pkg: &pkgContext{
pkg: importSpec(t, googleNativeSpec),
importBasePath: googleNativeImportBasePath,
pkgImportAliases: map[string]string{
"github.com/pulumi/pulumi-google-native/sdk/go/google/dns/v1": "dns",
},
},
token: "google-native:dns/v1:Policy",
expected: "dns.Policy",
},
}
//nolint:paralleltest // false positive because range var isn't used directly in t.Run(name) arg
for _, tt := range tests {
tt := tt
t.Run(tt.token+"=>"+tt.expected, func(t *testing.T) {
t.Parallel()
actual := tt.pkg.tokenToResource(tt.token)
assert.Equal(t, tt.expected, actual)
})
}
}
func importSpec(t *testing.T, spec schema.PackageSpec) *schema.Package {
importedPkg, err := schema.ImportSpec(spec, map[string]schema.Language{})
assert.NoError(t, err)
return importedPkg
}
func TestGenHeader(t *testing.T) {
t.Parallel()
pkg := &pkgContext{
tool: "a tool",
pkg: &schema.Package{Name: "test-pkg"},
}
s := func() string {
b := &bytes.Buffer{}
pkg.genHeader(b, []string{"pkg1", "example.com/foo/123-foo"}, nil)
return b.String()
}()
assert.Equal(t, `// Code generated by a tool DO NOT EDIT.
// *** WARNING: Do not edit by hand unless you're certain you know what you are doing! ***
package testpkg
import (
"pkg1"
"example.com/foo/123-foo"
)
`, s)
// Compliance is defined by https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source
autogenerated := regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.$`)
found := false
for _, l := range strings.Split(s, "\n") {
switch {
case autogenerated.Match([]byte(l)):
found = true
break
case l == "" || strings.HasPrefix(l, "//"):
default:
break
}
}
assert.Truef(t, found, `Didn't find a line that complies with "%v"`, autogenerated)
}
func TestTitle(t *testing.T) {
t.Parallel()
assert := assert.New(t)
assert.Equal("", Title(""))
assert.Equal("Plugh", Title("plugh"))
assert.Equal("WaldoThudFred", Title("WaldoThudFred"))
assert.Equal("WaldoThudFred", Title("waldoThudFred"))
assert.Equal("WaldoThudFred", Title("waldo-Thud-Fred"))
assert.Equal("WaldoThudFred", Title("waldo-ThudFred"))
assert.Equal("WaldoThud_Fred", Title("waldo-Thud_Fred"))
assert.Equal("WaldoThud_Fred", Title("waldo-thud_Fred"))
}