pulumi/pkg/codegen/testing/test/helpers.go

382 lines
9.4 KiB
Go
Raw Normal View History

// Copyright 2016-2021, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package test
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
2022-10-21 23:13:44 +00:00
"github.com/pulumi/pulumi/pkg/v3/codegen/testing/utils"
"github.com/pulumi/pulumi/pkg/v3/testing/integration"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/executable"
)
// GenPkgSignature corresponds to the shape of the codegen GeneratePackage functions.
type GenPkgSignature func(string, *schema.Package, map[string][]byte) (map[string][]byte, error)
// GeneratePackageFilesFromSchema loads a schema and generates files using the provided GeneratePackage function.
func GeneratePackageFilesFromSchema(schemaPath string, genPackageFunc GenPkgSignature) (map[string][]byte, error) {
// Read in, decode, and import the schema.
schemaBytes, err := os.ReadFile(schemaPath)
if err != nil {
return nil, err
}
ext := filepath.Ext(schemaPath)
var pkgSpec schema.PackageSpec
if ext == ".yaml" || ext == ".yml" {
err = yaml.Unmarshal(schemaBytes, &pkgSpec)
} else {
err = json.Unmarshal(schemaBytes, &pkgSpec)
}
if err != nil {
return nil, err
}
2022-10-21 23:13:44 +00:00
loader := schema.NewPluginLoader(utils.NewHost(testdataPath))
pkg, diags, err := schema.BindSpec(pkgSpec, loader)
if err != nil {
return nil, err
2022-10-21 23:13:44 +00:00
} else if diags.HasErrors() {
return nil, diags
}
return genPackageFunc("test", pkg, nil)
}
// LoadFiles loads the provided list of files from a directory.
2020-10-10 20:47:23 +00:00
func LoadFiles(dir, lang string, files []string) (map[string][]byte, error) {
result := map[string][]byte{}
for _, file := range files {
fileBytes, err := os.ReadFile(filepath.Join(dir, lang, file))
if err != nil {
return nil, err
}
result[file] = fileBytes
}
return result, nil
}
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if os.IsNotExist(err) {
return false, nil
}
if err == nil {
return true, nil
}
return false, err
}
// `LoadBaseline` loads the contents of the given baseline directory,
// by inspecting its `codegen-manifest.json`.
func LoadBaseline(dir, lang string) (map[string][]byte, error) {
cm := &codegenManifest{}
err := cm.load(filepath.Join(dir, lang))
if err != nil {
return nil, fmt.Errorf("Failed to load codegen-manifest.json: %w", err)
}
files := make(map[string][]byte)
for _, f := range cm.EmittedFiles {
bytes, err := os.ReadFile(filepath.Join(dir, lang, f))
if err != nil {
return nil, fmt.Errorf("Failed to load file %s referenced in codegen-manifest.json: %w", f, err)
}
files[f] = bytes
}
return files, nil
}
type codegenManifest struct {
EmittedFiles []string `json:"emittedFiles"`
}
func (cm *codegenManifest) load(dir string) error {
bytes, err := os.ReadFile(filepath.Join(dir, "codegen-manifest.json"))
if err != nil {
return err
}
return json.Unmarshal(bytes, cm)
}
func (cm *codegenManifest) save(dir string) error {
sort.Strings(cm.EmittedFiles)
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
err := enc.Encode(cm)
if err != nil {
return err
}
data := buf.Bytes()
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
return os.WriteFile(filepath.Join(dir, "codegen-manifest.json"), data, 0o600)
}
// ValidateFileEquality compares maps of files for equality.
func ValidateFileEquality(t *testing.T, actual, expected map[string][]byte) bool {
ok := true
for name, file := range expected {
_, inActual := actual[name]
if inActual {
if !assert.Equal(t, string(file), string(actual[name]), name) {
t.Logf("%s did not agree", name)
ok = false
}
} else {
t.Logf("File %s was expected but is missing from the actual fileset", name)
ok = false
}
}
for name := range actual {
if _, inExpected := expected[name]; !inExpected {
t.Logf("File %s from the actual fileset was not expected", name)
ok = false
}
}
return ok
}
// If PULUMI_ACCEPT is set, writes out actual output to the expected
// file set, so we can continue enjoying golden tests without manually
// modifying the expected output.
func RewriteFilesWhenPulumiAccept(t *testing.T, dir, lang string, actual map[string][]byte) bool {
if os.Getenv("PULUMI_ACCEPT") == "" {
return false
}
cm := &codegenManifest{}
baseline := filepath.Join(dir, lang)
// Remove the baseline directory's current contents.
_, err := os.ReadDir(baseline)
switch {
case err == nil:
err = os.RemoveAll(baseline)
require.NoError(t, err)
case os.IsNotExist(err):
// OK
default:
require.NoError(t, err)
}
for file, bytes := range actual {
relPath := filepath.FromSlash(file)
path := filepath.Join(dir, lang, relPath)
cm.EmittedFiles = append(cm.EmittedFiles, relPath)
err := writeFileEnsuringDir(path, bytes)
require.NoError(t, err)
}
err = cm.save(filepath.Join(dir, lang))
require.NoError(t, err)
return true
}
// Useful for populating code-generated destination
// `codeDir=$dir/$lang` with extra manually written files such as the
// unit test files. These files are copied from `$dir/$lang-extras`
// folder if present.
func CopyExtraFiles(t *testing.T, dir, lang string) {
codeDir := filepath.Join(dir, lang)
Enable perfsprint linter (#14813) <!--- Thanks so much for your contribution! If this is your first time contributing, please ensure that you have read the [CONTRIBUTING](https://github.com/pulumi/pulumi/blob/master/CONTRIBUTING.md) documentation. --> # Description <!--- Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. --> Prompted by a comment in another review: https://github.com/pulumi/pulumi/pull/14654#discussion_r1419995945 This lints that we don't use `fmt.Errorf` when `errors.New` will suffice, it also covers a load of other cases where `Sprintf` is sub-optimal. Most of these edits were made by running `perfsprint --fix`. ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [x] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [ ] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2023-12-12 12:19:42 +00:00
extrasDir := filepath.Join(dir, lang+"-extras")
gotExtras, err := PathExists(extrasDir)
if !gotExtras {
return
}
if err != nil {
require.NoError(t, err)
return
}
err = filepath.Walk(extrasDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
relPath, err := filepath.Rel(extrasDir, path)
if err != nil {
return err
}
destPath := filepath.Join(codeDir, relPath)
bytes, err := os.ReadFile(path)
if err != nil {
return err
}
err = writeFileEnsuringDir(destPath, bytes)
if err != nil {
return err
}
t.Logf("Copied %s to %s", path, destPath)
return nil
})
require.NoError(t, err)
}
func writeFileEnsuringDir(path string, bytes []byte) error {
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil && !os.IsExist(err) {
return err
}
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
return os.WriteFile(path, bytes, 0o600)
}
// CheckAllFilesGenerated ensures that the set of expected and actual files generated
// are exactly equivalent.
func CheckAllFilesGenerated(t *testing.T, actual, expected map[string][]byte) {
seen := map[string]bool{}
for x := range expected {
seen[x] = true
}
for a := range actual {
assert.Contains(t, seen, a, "Unexpected file generated: %s", a)
if seen[a] {
delete(seen, a)
}
}
for s := range seen {
assert.Fail(t, "No content generated for expected file %s", s)
}
}
// Validates a transformer on a single file.
func ValidateFileTransformer(
t *testing.T,
inputFile string,
expectedOutputFile string,
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
transformer func(reader io.Reader, writer io.Writer) error,
) {
reader, err := os.Open(inputFile)
if err != nil {
t.Error(err)
return
}
var buf bytes.Buffer
err = transformer(reader, &buf)
if err != nil {
t.Error(err)
return
}
actualBytes := buf.Bytes()
if os.Getenv("PULUMI_ACCEPT") != "" {
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
err := os.WriteFile(expectedOutputFile, actualBytes, 0o600)
if err != nil {
t.Error(err)
return
}
}
actual := map[string][]byte{expectedOutputFile: actualBytes}
expectedBytes, err := os.ReadFile(expectedOutputFile)
if err != nil {
t.Error(err)
return
}
expected := map[string][]byte{expectedOutputFile: expectedBytes}
ValidateFileEquality(t, actual, expected)
}
func RunCommand(t *testing.T, name string, cwd string, exec string, args ...string) {
RunCommandWithOptions(t, &integration.ProgramTestOptions{}, name, cwd, exec, args...)
}
func RunCommandWithOptions(
t *testing.T,
opts *integration.ProgramTestOptions,
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
name string, cwd string, exec string, args ...string,
) {
exec, err := executable.FindExecutable(exec)
if err != nil {
t.Error(err)
t.FailNow()
}
wd, err := filepath.Abs(cwd)
require.NoError(t, err)
var stdout, stderr bytes.Buffer
opts.Stdout = &stdout
opts.Stderr = &stderr
opts.Verbose = true
err = integration.RunCommand(t,
name,
append([]string{exec}, args...),
wd,
opts)
if !assert.NoError(t, err) {
stdout := stdout.String()
stderr := stderr.String()
if len(stdout) > 0 {
t.Logf("stdout: %s", stdout)
}
if len(stderr) > 0 {
t.Logf("stderr: %s", stderr)
}
t.FailNow()
}
}
type SchemaVersion = string
// Schemas are downloaded in the makefile, and the versions specified here
// should be in sync with the makefile.
const (
[program-gen] Fix panic when generating programs for MLC packages using external types (#15605) # Description For an MLC package such as `aws-static-website`, it has some types which are referenced from the `aws` package. Program-gen assumes packages are inferred from resources and invokes, not types which caused panics in Go (#15597), dotnet and python (https://github.com/pulumi/pulumi-converter-constructor-syntax/issues/2) This PR fixes those panics. In Go the panic was due to using package name instead of the package reference from the imported type. In dotnet and python was due to assuming no external type references. Now we generate nice code for all these languages. That said, there is still an issue of resolving imports for the packages of these external types. It works in Go, TypeScript doesn't need it but dotnet and python do. That is why the latter are added in `SkipCompile` in the test program. Fixes #15597 Fixes https://github.com/pulumi/pulumi-converter-constructor-syntax/issues/3 Fixes https://github.com/pulumi/pulumi-converter-constructor-syntax/issues/2 ## Checklist - [ ] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [x] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [x] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2024-03-10 17:23:15 +00:00
AwsSchema SchemaVersion = "4.26.0"
AzureNativeSchema SchemaVersion = "1.29.0"
AzureSchema SchemaVersion = "4.18.0"
KubernetesSchema SchemaVersion = "3.7.2"
RandomSchema SchemaVersion = "4.11.2"
EksSchema SchemaVersion = "0.37.1"
AwsStaticWebsiteSchema SchemaVersion = "0.4.0"
[program-gen/go,dotnet] Fixes emited code for object expressions assigned to properties of type Any (#15770) # Description Fixes #15769 by specifically handling object expressions that are annotated as `Any` and emitting the correct code. - In case of Go, expression `X` is emitted as `pulumi.Any(X)` where the type name here is `map[string]interface{}`. - In case of C#, we generate `Dictionary<string, object?>` expressions (similar to what we do inside `toJSON` calls) - Updates the test aws-native schema from 0.13.0 to 0.99.0 ## Checklist - [ ] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [x] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [x] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [x] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2024-03-24 00:06:57 +00:00
AwsNativeSchema SchemaVersion = "0.99.0"
)
[program-gen] Emit Output-returning JSON serialization methods without rewriting applies (#15371) ### Description A while ago we started implementing [specialized JSON serialization methods](https://github.com/pulumi/pulumi/issues/12519) for Pulumi programs which can accept nested outputs without having to rewrite and combine applies. - `Output.SerializeJson` in .NET - `pulumi.jsonStringify` in nodejs - `pulumi.Output.json_dumps` in Python This PR extends program-gen for TypeScript, C# and Python to start emitting these JSON serialization functions (when necessary). The PR special-cases the `toJSON` PCL function when rewriting applies so that nested outputs aren't rewritted. Example PCL program and generated results: > Also check out the downstream codegen tests to see improved generated examples ``` resource vpc "aws:ec2:Vpc" { cidrBlock = "10.100.0.0/16" instanceTenancy = "default" } resource policy "aws:iam/policy:Policy" { description = "test" policy = toJSON({ "Version" = "2012-10-17" "Interpolated" = "arn:${vpc.arn}:value" "Value" = vpc.id }) } ``` ### Generated TypeScript Before ```typescript import * as pulumi from "@pulumi/pulumi"; import * as aws from "@pulumi/aws"; const vpc = new aws.ec2.Vpc("vpc", { cidrBlock: "10.100.0.0/16", instanceTenancy: "default", }); const policy = new aws.iam.Policy("policy", { description: "test", policy: pulumi.all([vpc.arn, vpc.id]).apply(([arn, id]) => JSON.stringify({ Version: "2012-10-17", Interpolated: `arn:${arn}:value`, Value: id, })), }); ``` ### Generated TypeScript After ```typescript import * as pulumi from "@pulumi/pulumi"; import * as aws from "@pulumi/aws"; const vpc = new aws.ec2.Vpc("vpc", { cidrBlock: "10.100.0.0/16", instanceTenancy: "default", }); const policy = new aws.iam.Policy("policy", { description: "test", policy: pulumi.jsonStringify({ Version: "2012-10-17", Interpolated: pulumi.interpolate`arn:${vpc.arn}:value`, Value: vpc.id, }), }); ``` ### Generated Python Before ```python import pulumi import json import pulumi_aws as aws vpc = aws.ec2.Vpc("vpc", cidr_block="10.100.0.0/16", instance_tenancy="default") policy = aws.iam.Policy("policy", description="test", policy=pulumi.Output.all(vpc.arn, vpc.id).apply(lambda arn, id: json.dumps({ "Version": "2012-10-17", "Interpolated": f"arn:{arn}:value", "Value": id, }))) ``` ### Generated Python After ```python import pulumi import json import pulumi_aws as aws vpc = aws.ec2.Vpc("vpc", cidr_block="10.100.0.0/16", instance_tenancy="default") policy = aws.iam.Policy("policy", description="test", policy=pulumi.Output.json_dumps({ "Version": "2012-10-17", "Interpolated": vpc.arn.apply(lambda arn: f"arn:{arn}:value"), "Value": vpc.id, })) ``` ### Generated C# Before ```csharp using System.Collections.Generic; using System.Linq; using System.Text.Json; using Pulumi; using Aws = Pulumi.Aws; return await Deployment.RunAsync(() => { var vpc = new Aws.Ec2.Vpc("vpc", new() { CidrBlock = "10.100.0.0/16", InstanceTenancy = "default", }); var policy = new Aws.Iam.Policy("policy", new() { Description = "test", PolicyDocument = Output.Tuple(vpc.Arn, vpc.Id).Apply(values => { var arn = values.Item1; var id = values.Item2; return JsonSerializer.Serialize(new Dictionary<string, object?> { ["Version"] = "2012-10-17", ["Interpolated"] = $"arn:{arn}:value", ["Value"] = id, }); }), }); }); ``` ### Generated C# After ```csharp using System.Collections.Generic; using System.Linq; using System.Text.Json; using Pulumi; using Aws = Pulumi.Aws; return await Deployment.RunAsync(() => { var vpc = new Aws.Ec2.Vpc("vpc", new() { CidrBlock = "10.100.0.0/16", InstanceTenancy = "default", }); var policy = new Aws.Iam.Policy("policy", new() { Description = "test", PolicyDocument = Output.JsonSerialize(Output.Create(new Dictionary<string, object?> { ["Version"] = "2012-10-17", ["Interpolated"] = vpc.Arn.Apply(arn => $"arn:{arn}:value"), ["Value"] = vpc.Id, })), }); }); ``` ## Checklist - [ ] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [x] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [x] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [x] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2024-02-20 15:48:46 +00:00
// PulumiDotnetSDKVersion is the version of the Pulumi .NET SDK to use in program-gen tests
const PulumiDotnetSDKVersion = "3.66.2"