pulumi/pkg/backend/display/diff_test.go

178 lines
4.5 KiB
Go
Raw Permalink Normal View History

// Copyright 2016-2023, 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 display
// Note: to regenerate the baselines for these tests, run `go test` with `PULUMI_ACCEPT=true`.
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"testing"
"github.com/pulumi/pulumi/pkg/v3/engine"
"github.com/pulumi/pulumi/sdk/v3/go/common/apitype"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag/colors"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func loadEvents(path string) (events []engine.Event, err error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("opening '%v': %w", path, err)
}
defer contract.IgnoreClose(f)
dec := json.NewDecoder(f)
for {
var jsonEvent apitype.EngineEvent
if err = dec.Decode(&jsonEvent); err != nil {
if err == io.EOF {
break
}
return nil, fmt.Errorf("decoding event %d: %w", len(events), err)
}
event, err := ConvertJSONEvent(jsonEvent)
if err != nil {
return nil, fmt.Errorf("converting event %d: %w", len(events), err)
}
events = append(events, event)
}
// If there are no events or if the event stream does not terminate with a cancel event,
// synthesize one here.
if len(events) == 0 || events[len(events)-1].Type != engine.CancelEvent {
events = append(events, engine.NewCancelEvent())
}
return events, nil
}
func testDiffEvents(t *testing.T, path string, accept bool, truncateOutput bool) {
events, err := loadEvents(path)
require.NoError(t, err)
var expectedStdout []byte
var expectedStderr []byte
if !accept {
expectedStdout, err = os.ReadFile(path + ".stdout.txt")
require.NoError(t, err)
expectedStderr, err = os.ReadFile(path + ".stderr.txt")
require.NoError(t, err)
}
eventChannel, doneChannel := make(chan engine.Event), make(chan bool)
var stdout bytes.Buffer
var stderr bytes.Buffer
go ShowDiffEvents("test", eventChannel, doneChannel, Options{
Color: colors.Raw,
ShowConfig: true,
ShowReplacementSteps: true,
ShowSameResources: true,
ShowReads: true,
TruncateOutput: truncateOutput,
Stdout: &stdout,
Stderr: &stderr,
})
for _, e := range events {
eventChannel <- e
}
<-doneChannel
if !accept {
assert.Equal(t, string(expectedStdout), stdout.String())
assert.Equal(t, string(expectedStderr), stderr.String())
} else {
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(path+".stdout.txt", stdout.Bytes(), 0o600)
require.NoError(t, 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
err = os.WriteFile(path+".stderr.txt", stderr.Bytes(), 0o600)
require.NoError(t, err)
}
}
func TestDiffEvents(t *testing.T) {
t.Parallel()
accept := cmdutil.IsTruthy(os.Getenv("PULUMI_ACCEPT"))
entries, err := os.ReadDir("testdata/not-truncated")
require.NoError(t, err)
//nolint:paralleltest
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
continue
}
path := filepath.Join("testdata/not-truncated", entry.Name())
t.Run(entry.Name(), func(t *testing.T) {
t.Parallel()
testDiffEvents(t, path, accept, false)
})
}
entries, err = os.ReadDir("testdata/truncated")
require.NoError(t, err)
//nolint:paralleltest
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
continue
}
path := filepath.Join("testdata/truncated", entry.Name())
t.Run(entry.Name(), func(t *testing.T) {
t.Parallel()
testDiffEvents(t, path, accept, true)
})
}
}
Fix JSON/YAML diffs (#15171) <!--- 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. --> Fixes https://github.com/pulumi/pulumi/issues/13981. This regressed in https://github.com/pulumi/pulumi/pull/11803. I've added tests to this PR to show both the value diffing and text diffing for when the JSON/YAML string is different but the values are the same. ## 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. --> - [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-01-18 14:19:54 +00:00
func TestJsonYamlDiff(t *testing.T) {
t.Parallel()
accept := cmdutil.IsTruthy(os.Getenv("PULUMI_ACCEPT"))
entries, err := os.ReadDir("testdata/json-yaml")
require.NoError(t, err)
//nolint:paralleltest
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
continue
}
path := filepath.Join("testdata/json-yaml", entry.Name())
t.Run(entry.Name(), func(t *testing.T) {
t.Parallel()
testDiffEvents(t, path, accept, false)
})
}
}