Skip to content

Commit

Permalink
chore: fixed working-directory in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
giautm committed Dec 24, 2024
1 parent c54b5f2 commit 1a774f0
Show file tree
Hide file tree
Showing 17 changed files with 112 additions and 178 deletions.
76 changes: 11 additions & 65 deletions atlasaction/action_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2181,34 +2181,37 @@ func renderTemplate[T any](ts *testscript.TestScript, neg bool, args []string) {
ts.Check(err)
}

func TestMain(m *testing.M) {
os.Exit(testscript.RunMain(m, map[string]func() int{
"atlas-action": func() int {
return atlasaction.Main("testscript", "dev")
},
}))
}

func TestGitHubActions(t *testing.T) {
var (
actions = "actions"
output = filepath.Join(actions, "output.txt")
summary = filepath.Join(actions, "summary.txt")
)
wd, err := os.Getwd()
require.NoError(t, err)
testscript.Run(t, testscript.Params{
Dir: filepath.Join("testdata", "github"),
Setup: func(e *testscript.Env) (err error) {
dir := filepath.Join(e.WorkDir, actions)
if err := os.Mkdir(dir, 0700); err != nil {
return err
}
e.Setenv("SOURCE", wd)
e.Setenv("GITHUB_ACTIONS", "true")
e.Setenv("GITHUB_ENV", filepath.Join(dir, "env.txt"))
e.Setenv("GITHUB_OUTPUT", filepath.Join(dir, "output.txt"))
e.Setenv("GITHUB_STEP_SUMMARY", filepath.Join(dir, "summary.txt"))
c, err := atlasexec.NewClient(e.WorkDir, "atlas")
if err != nil {
return err
}
// Create a new actions for each test.
e.Values[atlasKey{}] = &atlasClient{c}
return nil
},
Cmds: map[string]func(ts *testscript.TestScript, neg bool, args []string){
"atlas-action": atlasAction,
"mock-atlas": mockAtlasOutput,
"summary": func(ts *testscript.TestScript, neg bool, args []string) {
if len(args) == 0 {
_, err := os.Stat(ts.MkAbs(summary))
Expand Down Expand Up @@ -2247,63 +2250,6 @@ func TestGitHubActions(t *testing.T) {
})
}

type (
atlasKey struct{}
atlasClient struct {
atlasaction.AtlasExec
}
)

func atlasAction(ts *testscript.TestScript, neg bool, args []string) {
if len(args) != 1 {
ts.Fatalf("usage: atlas-action <action>")
}
client, ok := ts.Value(atlasKey{}).(*atlasClient)
if !ok || client == nil {
ts.Fatalf("client not found")
}
// The action need to be create for each call to read correct inputs
act, err := atlasaction.New(
atlasaction.WithGetenv(ts.Getenv),
atlasaction.WithOut(ts.Stdout()),
atlasaction.WithAtlas(client.AtlasExec),
atlasaction.WithVersion("testscript"),
)
ts.Check(err)
action := args[0]
ts.Setenv("ATLAS_ACTION_COMMAND", action)
ts.Defer(func() {
ts.Setenv("ATLAS_ACTION_COMMAND", "")
})
// Run the action!
switch err := act.Run(context.Background(), action); {
case !neg:
ts.Check(err)
case err == nil:
ts.Fatalf("expected fail")
case neg:
// Print the error to asserting on the testscript
fmt.Fprint(ts.Stderr(), err.Error())
}
}

func mockAtlasOutput(ts *testscript.TestScript, neg bool, args []string) {
if len(args) != 1 {
ts.Fatalf("usage: mock-atlas <dir>")
}
client, ok := ts.Value(atlasKey{}).(*atlasClient)
if !ok || client == nil {
ts.Fatalf("client not found")
}
m, err := atlasexec.NewClient("", "./mock-atlas.sh")
ts.Check(err)
ts.Check(m.SetEnv(map[string]string{
"TEST_BATCH": args[0],
}))
// Replace the atlas client with a mock client.
client.AtlasExec = m
}

func cmpFiles(ts *testscript.TestScript, neg bool, name1, name2 string) {
text1 := ts.ReadFile(name1)
data, err := os.ReadFile(ts.MkAbs(name2))
Expand Down
13 changes: 4 additions & 9 deletions atlasaction/bitbucket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,31 @@ import (
"path/filepath"
"testing"

"ariga.io/atlas-go-sdk/atlasexec"
"github.com/rogpeppe/go-internal/testscript"
"github.com/stretchr/testify/require"
)

func TestBitbucketPipe(t *testing.T) {
var (
actions = "actions"
outputs = filepath.Join("outputs.sh")
)
wd, err := os.Getwd()
require.NoError(t, err)
testscript.Run(t, testscript.Params{
Dir: filepath.Join("testdata", "bitbucket"),
Setup: func(e *testscript.Env) (err error) {
dir := filepath.Join(e.WorkDir, actions)
if err := os.Mkdir(dir, 0700); err != nil {
return err
}
e.Setenv("SOURCE", wd)
e.Setenv("BITBUCKET_PIPELINE_UUID", "fbfb4205-c666-42ed-983a-d27f47f2aad2")
e.Setenv("BITBUCKET_PIPE_STORAGE_DIR", dir)
e.Setenv("BITBUCKET_CLONE_DIR", e.WorkDir)
c, err := atlasexec.NewClient(e.WorkDir, "atlas")
if err != nil {
return err
}
// Create a new actions for each test.
e.Values[atlasKey{}] = &atlasClient{c}
return nil
},
Cmds: map[string]func(ts *testscript.TestScript, neg bool, args []string){
"atlas-action": atlasAction,
"mock-atlas": mockAtlasOutput,
"output": func(ts *testscript.TestScript, neg bool, args []string) {
if len(args) == 0 {
_, err := os.Stat(ts.MkAbs(outputs))
Expand Down
12 changes: 3 additions & 9 deletions atlasaction/circleci_action_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"testing"

"ariga.io/atlas-action/atlasaction"
"ariga.io/atlas-go-sdk/atlasexec"
"github.com/rogpeppe/go-internal/testscript"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -63,28 +62,23 @@ func TestCircleCI(t *testing.T) {
actions = "actions"
output = filepath.Join(actions, "output.txt")
)
wd, err := os.Getwd()
require.NoError(t, err)
testscript.Run(t, testscript.Params{
Dir: filepath.Join("testdata", "circleci"),
Setup: func(e *testscript.Env) (err error) {
dir := filepath.Join(e.WorkDir, actions)
if err := os.Mkdir(dir, 0700); err != nil {
return err
}
e.Setenv("SOURCE", wd)
e.Setenv("CIRCLECI", "true")
e.Setenv("CIRCLE_PROJECT_REPONAME", "atlas-orb")
e.Setenv("CIRCLE_SHA1", "1234567890")
e.Setenv("BASH_ENV", filepath.Join(dir, "output.txt"))
c, err := atlasexec.NewClient(e.WorkDir, "atlas")
if err != nil {
return err
}
// Create a new actions for each test.
e.Values[atlasKey{}] = &atlasClient{c}
return nil
},
Cmds: map[string]func(ts *testscript.TestScript, neg bool, args []string){
"atlas-action": atlasAction,
"mock-atlas": mockAtlasOutput,
"output": func(ts *testscript.TestScript, neg bool, args []string) {
if len(args) == 0 {
_, err := os.Stat(ts.MkAbs(output))
Expand Down
13 changes: 4 additions & 9 deletions atlasaction/gitlab_ci_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import (
"testing"

"ariga.io/atlas-action/atlasaction"
"ariga.io/atlas-go-sdk/atlasexec"
"github.com/gorilla/mux"
"github.com/rogpeppe/go-internal/testscript"
"github.com/stretchr/testify/require"
)

func newMockHandler(dir string) http.Handler {
Expand Down Expand Up @@ -88,6 +88,8 @@ func newMockHandler(dir string) http.Handler {
}

func TestGitlabCI(t *testing.T) {
wd, err := os.Getwd()
require.NoError(t, err)
testscript.Run(t, testscript.Params{
Dir: "testdata/gitlab",
Setup: func(e *testscript.Env) error {
Expand All @@ -97,21 +99,14 @@ func TestGitlabCI(t *testing.T) {
return err
}
e.Defer(srv.Close)
e.Setenv("SOURCE", wd)
e.Setenv("CI_API_V4_URL", srv.URL)
e.Setenv("CI_PROJECT_ID", "1")
e.Setenv("GITLAB_CI", "true")
e.Setenv("GITLAB_TOKEN", "token")
c, err := atlasexec.NewClient(e.WorkDir, "atlas")
if err != nil {
return err
}
// Create a new actions for each test.
e.Values[atlasKey{}] = &atlasClient{c}
return nil
},
Cmds: map[string]func(ts *testscript.TestScript, neg bool, args []string){
"atlas-action": atlasAction,
"mock-atlas": mockAtlasOutput,
"output": func(ts *testscript.TestScript, neg bool, args []string) {
if len(args) == 0 {
_, err := os.Stat(ts.MkAbs(".env"))
Expand Down
60 changes: 60 additions & 0 deletions atlasaction/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package atlasaction

import (
"context"
"errors"
"fmt"
"os"

"ariga.io/atlas-action/atlasaction/cloud"
"github.com/alecthomas/kong"
)

func Main(version, commit string) int {
atlasPath := "atlas"
if p := os.Getenv("ATLAS_PATH"); p != "" {
// The environment can provide the path to the atlas-cli binary.
//
// This is useful when running the action in a Docker container,
// and the user can mount the atlas-cli binary in the container and set the
// ATLAS_PATH environment variable to the path of the binary.
atlasPath = p
}
act, err := New(
WithAtlasPath(atlasPath),
WithCloudClient(cloud.New),
WithVersion(version),
)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to run action in the current environment: %s\n", err)
os.Exit(1)
}
cli := kong.Parse(
&RunActionCmd{},
kong.BindTo(context.Background(), (*context.Context)(nil)),
kong.Vars{
"version": fmt.Sprintf("atlas-action version %s-%s\n", version, commit),
},
)
if err := cli.Run(act); err != nil {
if uerr := errors.Unwrap(err); uerr != nil {
err = uerr
}
act.Fatalf(err.Error())
}
return 0
}

// RunActionCmd is a command to run one of the Atlas GitHub Actions.
type RunActionCmd struct {
Action string `help:"Command to run" required:"" env:"ATLAS_ACTION"`
Version kong.VersionFlag `name:"version" help:"Print version information and quit"`
}

func (r *RunActionCmd) Run(ctx context.Context, a *Actions) error {
_ = os.Setenv("ATLAS_ACTION_COMMAND", r.Action)
defer func() {
_ = os.Unsetenv("ATLAS_ACTION_COMMAND")
}()
return a.Run(ctx, r.Action)
}
4 changes: 2 additions & 2 deletions cmd/atlas-action/main_test.go → atlasaction/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.

package main
package atlasaction_test

import (
"context"
Expand All @@ -19,7 +19,7 @@ func TestRunAction_Run(t *testing.T) {
require.NoError(t, err)
act := atlasaction.NewGHAction(os.Getenv, os.Stdout)
t.Run("fake", func(t *testing.T) {
r := &RunActionCmd{Action: "fake"}
r := &atlasaction.RunActionCmd{Action: "fake"}
c, err := atlasaction.New(atlasaction.WithAction(act), atlasaction.WithAtlas(client))
require.NoError(t, err)
err = r.Run(context.Background(), c)
Expand Down
6 changes: 3 additions & 3 deletions atlasaction/testdata/bitbucket/schema-push.txtar
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
# Mock atlas command outputs
mock-atlas $WORK/schema-push
env ATLAS_PATH=$SOURCE/mock-atlas.sh TEST_BATCH=$WORK/schema-push
# Setup the action input variables
env ATLAS_INPUT_ENV=test
env ATLAS_INPUT_LATEST=true

# Run the action without a tag
atlas-action schema/push
atlas-action --action=schema/push

# Run the action with a tag
env ATLAS_INPUT_TAG=98765
atlas-action schema/push
atlas-action --action=schema/push

exec cat .atlas-action/outputs.sh
output outputs.sh
Expand Down
4 changes: 2 additions & 2 deletions atlasaction/testdata/circleci/migrate-lint.txtar
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Mock the atlas command outputs
mock-atlas $WORK/migrate-lint
env ATLAS_PATH=$SOURCE/mock-atlas.sh TEST_BATCH=$WORK/migrate-lint
# Setup the action input variables
env INPUT_CONFIG=file://testdata/config/atlas.hcl
env INPUT_ENV=test
Expand All @@ -12,7 +12,7 @@ env INPUT_RUN=example

# The action's output should append the existing outputs
cp output-pre.txt actions/output.txt
atlas-action migrate/lint
atlas-action --action=migrate/lint
output output.txt

-- migrate-lint/1/args --
Expand Down
4 changes: 2 additions & 2 deletions atlasaction/testdata/github/migrate-lint.txtar
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Mock the atlas command outputs
mock-atlas $WORK/migrate-lint
env ATLAS_PATH=$SOURCE/mock-atlas.sh TEST_BATCH=$WORK/migrate-lint
# Setup the action input variables
env INPUT_CONFIG=file://testdata/config/atlas.hcl
env INPUT_ENV=test
Expand All @@ -10,7 +10,7 @@ env INPUT_DIR=file://testdata/migrations
env INPUT_DEV_URL=sqlite://file?mode=memory
env INPUT_RUN=example

atlas-action migrate/lint
atlas-action --action=migrate/lint
output output.txt

-- migrate-lint/1/args --
Expand Down
6 changes: 3 additions & 3 deletions atlasaction/testdata/github/migrate-test.txtar
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Mock the atlas command outputs
mock-atlas $WORK/migrate-test
env ATLAS_PATH=$SOURCE/mock-atlas.sh TEST_BATCH=$WORK/migrate-test
# Setup the action input variables
env INPUT_CONFIG=file://testdata/config/atlas.hcl
env INPUT_ENV=test
Expand All @@ -8,12 +8,12 @@ env INPUT_DIR=file://testdata/migrations
env INPUT_DEV_URL=sqlite://file?mode=memory
env INPUT_RUN=example

atlas-action migrate/test
atlas-action --action=migrate/test
stdout '`atlas migrate test` completed successfully, no issues found'
stdout 'Success'
! output

! atlas-action migrate/test
! atlas-action --action=migrate/test
stderr '`atlas migrate test` completed with errors:'
stderr 'Failure'
! output
Expand Down
4 changes: 2 additions & 2 deletions atlasaction/testdata/github/schema-apply-envs.txtar
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# Mock the atlas command outputs
mock-atlas $WORK/schema-apply
env ATLAS_PATH=$SOURCE/mock-atlas.sh TEST_BATCH=$WORK/schema-apply
# Setup the action input variables
env INPUT_ENV=test
env INPUT_PLAN=file://20240910173744.plan.hcl
# Run the action
! atlas-action schema/apply
! atlas-action --action=schema/apply
stdout '"atlas schema apply" completed successfully on the target "sqlite://local-bu.db"'
stdout '"atlas schema apply" completed successfully on the target "sqlite://local-pi.db"'
stdout '"atlas schema apply" completed successfully on the target "sqlite://local-su.db"'
Expand Down
Loading

0 comments on commit 1a774f0

Please sign in to comment.