pulumi/pkg/testing/integration/util.go

245 lines
6.2 KiB
Go
Raw Permalink Normal View History

2018-05-22 19:43:36 +00:00
// Copyright 2016-2018, 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 integration
import (
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
// DecodeMapString takes a string of the form key1=value1:key2=value2 and returns a go map.
func DecodeMapString(val string) (map[string]string, error) {
newMap := make(map[string]string)
if val != "" {
for _, overrideClause := range strings.Split(val, ":") {
data := strings.Split(overrideClause, "=")
if len(data) != 2 {
return nil, fmt.Errorf(
"could not decode %s as an override, should be of the form <package>=<version>",
overrideClause)
}
packageName := data[0]
packageVersion := data[1]
newMap[packageName] = packageVersion
}
}
return newMap, nil
}
// ReplaceInFile does a find and replace for a given string within a file.
func ReplaceInFile(old, new, path string) error {
rawContents, err := os.ReadFile(path)
if err != nil {
return err
}
newContents := strings.ReplaceAll(string(rawContents), old, new)
return os.WriteFile(path, []byte(newContents), os.ModePerm)
}
// getCmdBin returns the binary named bin in location loc or, if it hasn't yet been initialized, will lazily
// populate it by either using the default def or, if empty, looking on the current $PATH.
func getCmdBin(loc *string, bin, def string) (string, error) {
if *loc == "" {
*loc = def
if *loc == "" {
var err error
*loc, err = exec.LookPath(bin)
if err != nil {
return "", fmt.Errorf("Expected to find `%s` binary on $PATH: %w", bin, err)
}
}
}
return *loc, nil
}
func uniqueSuffix() string {
// .<timestamp>.<five random hex characters>
timestamp := time.Now().Format("20060102-150405")
suffix, err := resource.NewUniqueHex("."+timestamp+".", 5, -1)
contract.AssertNoErrorf(err, "could not generate random suffix")
return suffix
}
const (
commandOutputFolderName = "command-output"
)
func writeCommandOutput(commandName, runDir string, output []byte) (string, error) {
logFileDir := filepath.Join(runDir, commandOutputFolderName)
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(logFileDir, 0o700); err != nil {
return "", fmt.Errorf("Failed to create '%s': %w", logFileDir, err)
}
logFile := filepath.Join(logFileDir, commandName+uniqueSuffix()+".log")
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.WriteFile(logFile, output, 0o600); err != nil {
return "", fmt.Errorf("Failed to write '%s': %w", logFile, err)
}
return logFile, nil
}
// CopyFile copies a single file from src to dst
// From https://blog.depado.eu/post/copy-files-and-directories-in-go
func CopyFile(src, dst string) error {
var err error
var srcfd *os.File
var dstfd *os.File
var srcinfo os.FileInfo
var n int64
if srcfd, err = os.Open(src); err != nil {
return err
}
defer srcfd.Close()
if dstfd, err = os.Create(dst); err != nil {
return err
}
defer dstfd.Close()
if n, err = io.Copy(dstfd, srcfd); err != nil {
return err
}
if srcinfo, err = os.Stat(src); err != nil {
return err
}
if n != srcinfo.Size() {
return fmt.Errorf("failed to copy all bytes from %v to %v", src, dst)
}
return os.Chmod(dst, srcinfo.Mode())
}
// CopyDir copies a whole directory recursively
// From https://blog.depado.eu/post/copy-files-and-directories-in-go
func CopyDir(src, dst string) error {
var err error
var fds []os.DirEntry
var srcinfo os.FileInfo
if srcinfo, err = os.Stat(src); err != nil {
return err
}
if err = os.MkdirAll(dst, srcinfo.Mode()); err != nil {
return err
}
if fds, err = os.ReadDir(src); err != nil {
return err
}
for _, fd := range fds {
srcfp := path.Join(src, fd.Name())
dstfp := path.Join(dst, fd.Name())
if fd.IsDir() {
if err = CopyDir(srcfp, dstfp); err != nil {
fmt.Println(err)
}
} else {
if err = CopyFile(srcfp, dstfp); err != nil {
fmt.Println(err)
}
}
}
return nil
}
// AssertHTTPResultWithRetry attempts to assert that an HTTP endpoint exists
// and evaluate its response.
2021-11-09 23:41:28 +00:00
func AssertHTTPResultWithRetry(
t *testing.T,
output interface{},
headers map[string]string,
maxWait time.Duration,
check func(string) bool,
) bool {
hostname, ok := output.(string)
if !assert.True(t, ok, fmt.Sprintf("expected `%s` output", output)) {
return false
}
if !(strings.HasPrefix(hostname, "http://") || strings.HasPrefix(hostname, "https://")) {
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
hostname = "http://" + hostname
}
var err error
var resp *http.Response
startTime := time.Now()
count, sleep := 0, 0
for {
now := time.Now()
req, err := http.NewRequest("GET", hostname, nil)
if !assert.NoError(t, err, "error reading request: %v", err) {
return false
}
for k, v := range headers {
// Host header cannot be set via req.Header.Set(), and must be set
// directly.
if strings.ToLower(k) == "host" {
req.Host = v
continue
}
req.Header.Set(k, v)
}
client := &http.Client{Timeout: time.Second * 10}
resp, err = client.Do(req)
if err == nil && resp.StatusCode == 200 {
break
}
if now.Sub(startTime) >= maxWait {
t.Logf("Timeout after %v. Unable to http.get %v successfully.", maxWait, hostname)
break
}
count++
// delay 10s, 20s, then 30s and stay at 30s
if sleep > 30 {
sleep = 30
} else {
sleep += 10
}
time.Sleep(time.Duration(sleep) * time.Second)
t.Logf("Http Error: %v\n", err)
t.Logf(" Retry: %v, elapsed wait: %v, max wait %v\n", count, now.Sub(startTime), maxWait)
}
if !assert.NoError(t, err) {
return false
}
// Read the body
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if !assert.NoError(t, err) {
return false
}
// Verify it matches expectations
return check(string(body))
}