pulumi/sdk/go/common/workspace/paths_test.go

208 lines
6.8 KiB
Go
Raw Normal View History

// Copyright 2016-2022, 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 workspace
import (
"os"
"path/filepath"
"testing"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// In the tests below we use temporary directories and then expect DetectProjectAndPath to return a path to
// that directory. However DetectProjectAndPath will do symlink resolution, while t.TempDir() normally does
// not. This can lead to asserts especially on macos where TmpDir will have returned /var/folders/XX, but
// after sym link resolution that is /private/var/folders/XX.
func mkTempDir(t *testing.T) string {
tmpDir := t.TempDir()
result, err := filepath.EvalSymlinks(tmpDir)
assert.NoError(t, err)
return result
}
//nolint:paralleltest // Theses test use and change the current working directory
func TestDetectProjectAndPath(t *testing.T) {
tmpDir := mkTempDir(t)
cwd, err := os.Getwd()
assert.NoError(t, err)
defer func() { err := os.Chdir(cwd); assert.NoError(t, err) }()
err = os.Chdir(tmpDir)
assert.NoError(t, err)
yamlPath := filepath.Join(tmpDir, "Pulumi.yaml")
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
yamlContents := "name: some_project\ndescription: Some project\nruntime: nodejs\n"
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(yamlPath, []byte(yamlContents), 0o600)
assert.NoError(t, err)
project, path, err := DetectProjectAndPath()
assert.NoError(t, err)
assert.Equal(t, yamlPath, path)
assert.Equal(t, tokens.PackageName("some_project"), project.Name)
assert.Equal(t, "Some project", *project.Description)
assert.Equal(t, "nodejs", project.Runtime.name)
}
//nolint:paralleltest // Theses test use and change the current working directory
func TestProjectStackPath(t *testing.T) {
expectedPath := func(expectedPath string) func(t *testing.T, projectDir, path string, err error) {
return func(t *testing.T, projectDir, path string, err error) {
assert.NoError(t, err)
assert.Equal(t, filepath.Join(projectDir, expectedPath), path)
}
}
tests := []struct {
name string
yamlContents string
validate func(t *testing.T, projectDir, path string, err error)
}{{
"WithoutStackConfigDir",
"name: some_project\ndescription: Some project\nruntime: nodejs\n",
expectedPath("Pulumi.my_stack.yaml"),
}, {
"WithStackConfigDir",
"name: some_project\ndescription: Some project\nruntime: nodejs\nstackConfigDir: stacks\n",
expectedPath(filepath.Join("stacks", "Pulumi.my_stack.yaml")),
}, {
"WithConfig",
"name: some_project\ndescription: Some project\nruntime: nodejs\nconfig: stacks\n",
expectedPath(filepath.Join("stacks", "Pulumi.my_stack.yaml")),
}, {
"WithBoth",
"name: some_project\ndescription: Some project\nruntime: nodejs\nconfig: stacksA\nstackConfigDir: stacksB\n",
func(t *testing.T, projectDir, path string, err error) {
errorMsg := "Should not use both config and stackConfigDir to define the stack directory. " +
"Use only stackConfigDir instead."
assert.EqualError(t, err, errorMsg)
},
}}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
tmpDir := mkTempDir(t)
cwd, err := os.Getwd()
assert.NoError(t, err)
defer func() { err := os.Chdir(cwd); assert.NoError(t, err) }()
err = os.Chdir(tmpDir)
assert.NoError(t, err)
err = os.WriteFile(
filepath.Join(tmpDir, "Pulumi.yaml"),
[]byte(tt.yamlContents),
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
0o600)
assert.NoError(t, err)
_, path, err := DetectProjectStackPath("my_stack")
tt.validate(t, tmpDir, path, err)
})
}
}
//nolint:paralleltest // Theses test use and change the current working directory
func TestDetectProjectUnreadableParent(t *testing.T) {
// Regression test for https://github.com/pulumi/pulumi/issues/12481
tmpDir := mkTempDir(t)
cwd, err := os.Getwd()
require.NoError(t, err)
defer func() { err := os.Chdir(cwd); assert.NoError(t, err) }()
// unreadable parent directory
parentDir := filepath.Join(tmpDir, "root")
err = os.Mkdir(parentDir, 0o300)
require.NoError(t, err)
// Make it readable so we can clean it up later
defer func() { err := os.Chmod(parentDir, 0o700); assert.NoError(t, err) }()
// readable current directory
currentDir := filepath.Join(parentDir, "current")
err = os.Mkdir(currentDir, 0o700)
require.NoError(t, err)
err = os.Chdir(currentDir)
require.NoError(t, err)
_, _, err = DetectProjectAndPath()
assert.ErrorIs(t, err, ErrProjectNotFound)
}
Update pu/pu to support the new settings pull command + new deployment file (#16398) <!--- 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 - Add new deployment settings pull command: this command will pull the deployment settings from pulumi cloud and generate the new deployment file. For now it will be hidden until we have completed the whole feature. - Add support for the new deployment file, this will contain all the deployment related information (for now just the settings), example: ``` settings: -executorContext: {} sourceContext: git: branch: main repoDir: . gitHub: repository: glena/test-action deployCommits: true previewPullRequests: false operationContext: preRunCommands: [] operation: "" environmentVariables: {} options: skipInstallDependencies: false skipIntermediateDeployments: true shell: "" deleteAfterDestroy: false remediateIfDriftDetected: false agentPoolID: ... ``` Fixes https://github.com/pulumi/pulumi-service/issues/20306 ## Checklist - [ ] I have run `make tidy` to update any new dependencies - [ ] 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. --> - [ ] 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. --> --------- Co-authored-by: Komal <komal@pulumi.com> Co-authored-by: Will Jones <will@sacharissa.co.uk>
2024-06-18 13:24:01 +00:00
//nolint:paralleltest // These tests use and change the current working directory
func TestDetectProjectStackDeploymentPath(t *testing.T) {
tmpDir := mkTempDir(t)
cwd, err := os.Getwd()
assert.NoError(t, err)
defer func() { err := os.Chdir(cwd); assert.NoError(t, err) }()
err = os.Chdir(tmpDir)
assert.NoError(t, err)
yamlPath := filepath.Join(tmpDir, "Pulumi.yaml")
yamlContents := `
name: some_project
description: Some project
runtime: nodejs`
err = os.WriteFile(yamlPath, []byte(yamlContents), 0o600)
assert.NoError(t, err)
yamlDeployPath := filepath.Join(tmpDir, "Pulumi.stack.deploy.yaml")
yamlDeployContents := ""
err = os.WriteFile(yamlDeployPath, []byte(yamlDeployContents), 0o600)
assert.NoError(t, err)
path, err := DetectProjectStackDeploymentPath("stack")
assert.NoError(t, err)
assert.Equal(t, yamlDeployPath, path)
}
func TestDetectPolicyPackPathAt(t *testing.T) {
t.Parallel()
tmpDir := mkTempDir(t)
// No policy pack file, return empty string
path, err := DetectPolicyPackPathAt(tmpDir)
require.NoError(t, err)
require.Equal(t, "", path)
// Create a PolicyPack.yaml
policyPackPath := filepath.Join(tmpDir, "PulumiPolicy.yaml")
yamlContents := "runtime: nodejs\n"
require.NoError(t, os.WriteFile(policyPackPath, []byte(yamlContents), 0o600))
path, err = DetectPolicyPackPathAt(tmpDir)
require.NoError(t, err)
require.Equal(t, policyPackPath, path)
// Check that we can also detect a PolicyPack.json
require.NoError(t, os.Remove(policyPackPath))
policyPackPath = filepath.Join(tmpDir, "PulumiPolicy.json")
jsonContents := `{"runtime": "nodejs"}`
require.NoError(t, os.WriteFile(policyPackPath, []byte(jsonContents), 0o600))
path, err = DetectPolicyPackPathAt(tmpDir)
require.NoError(t, err)
require.Equal(t, policyPackPath, path)
// Return an empty string if the path is a directory
require.NoError(t, os.Remove(policyPackPath))
require.NoError(t, os.Mkdir(policyPackPath, 0o700))
path, err = DetectPolicyPackPathAt(tmpDir)
require.NoError(t, err)
require.Equal(t, "", path)
}