Skip to content

Commit

Permalink
Refactor cmd/ to get rid of most direct os package access
Browse files Browse the repository at this point in the history
This makes everything much more easily testable!
  • Loading branch information
na-- committed Mar 6, 2022
1 parent 0245af8 commit c090d0c
Show file tree
Hide file tree
Showing 28 changed files with 708 additions and 756 deletions.
30 changes: 14 additions & 16 deletions cmd/archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,6 @@
package cmd

import (
"os"

"github.com/sirupsen/logrus"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/spf13/pflag"

Expand All @@ -33,7 +29,8 @@ import (
"go.k6.io/k6/lib/metrics"
)

func getArchiveCmd(logger *logrus.Logger, globalFlags *commandFlags) *cobra.Command {
func getArchiveCmd(globalState *globalState) *cobra.Command { // nolint: funlen
archiveOut := "archive.tar"
// archiveCmd represents the archive command
archiveCmd := &cobra.Command{
Use: "archive",
Expand All @@ -49,19 +46,22 @@ An archive is a fully self-contained test run, and can be executed identically e
k6 run myarchive.tar`[1:],
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
src, filesystems, err := readSource(args[0], logger)
src, filesystems, err := readSource(globalState, args[0])
if err != nil {
return err
}

runtimeOptions, err := getRuntimeOptions(cmd.Flags(), buildEnvMap(os.Environ()))
runtimeOptions, err := getRuntimeOptions(cmd.Flags(), globalState.envVars)
if err != nil {
return err
}

registry := metrics.NewRegistry()
builtinMetrics := metrics.RegisterBuiltinMetrics(registry)
r, err := newRunner(logger, src, globalFlags.runType, filesystems, runtimeOptions, builtinMetrics, registry)
r, err := newRunner(
globalState.logger, src, globalState.flags.runType,
filesystems, runtimeOptions, builtinMetrics, registry,
)
if err != nil {
return err
}
Expand All @@ -70,9 +70,7 @@ An archive is a fully self-contained test run, and can be executed identically e
if err != nil {
return err
}
conf, err := getConsolidatedConfig(
afero.NewOsFs(), Config{Options: cliOpts}, r.GetOptions(), buildEnvMap(os.Environ()), globalFlags,
)
conf, err := getConsolidatedConfig(globalState, Config{Options: cliOpts}, r.GetOptions())
if err != nil {
return err
}
Expand All @@ -89,7 +87,7 @@ An archive is a fully self-contained test run, and can be executed identically e
}
}

_, err = deriveAndValidateConfig(conf, r.IsExecutable, logger)
_, err = deriveAndValidateConfig(conf, r.IsExecutable, globalState.logger)
if err != nil {
return err
}
Expand All @@ -101,7 +99,7 @@ An archive is a fully self-contained test run, and can be executed identically e

// Archive.
arc := r.MakeArchive()
f, err := os.Create(globalFlags.archiveOut)
f, err := globalState.fs.Create(archiveOut)
if err != nil {
return err
}
Expand All @@ -115,16 +113,16 @@ An archive is a fully self-contained test run, and can be executed identically e
}

archiveCmd.Flags().SortFlags = false
archiveCmd.Flags().AddFlagSet(archiveCmdFlagSet(globalFlags))
archiveCmd.Flags().AddFlagSet(archiveCmdFlagSet(&archiveOut))

return archiveCmd
}

func archiveCmdFlagSet(globalFlags *commandFlags) *pflag.FlagSet {
func archiveCmdFlagSet(archiveOut *string) *pflag.FlagSet {
flags := pflag.NewFlagSet("", pflag.ContinueOnError)
flags.SortFlags = false
flags.AddFlagSet(optionFlagSet())
flags.AddFlagSet(runtimeOptionFlagSet(false))
flags.StringVarP(&globalFlags.archiveOut, "archive-out", "O", globalFlags.archiveOut, "archive output filename")
flags.StringVarP(archiveOut, "archive-out", "O", *archiveOut, "archive output filename")
return flags
}
29 changes: 11 additions & 18 deletions cmd/archive_test.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package cmd

import (
"os"
"io/ioutil"
"path/filepath"
"testing"

"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.k6.io/k6/errext"
"go.k6.io/k6/errext/exitcodes"
"go.k6.io/k6/lib/testutils"
)

func TestArchiveThresholds(t *testing.T) {
Expand Down Expand Up @@ -41,25 +41,17 @@ func TestArchiveThresholds(t *testing.T) {
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()

tmpDir, err := os.MkdirTemp("", "k6archivetest")
testScript, err := ioutil.ReadFile(testCase.testFilename)
require.NoError(t, err)
defer func() {
require.NoError(t, os.RemoveAll(tmpDir))
}()
tmpPath := filepath.Join(tmpDir, "archive.tar")

cmd := getArchiveCmd(testutils.NewLogger(t), newCommandFlags())
filename, err := filepath.Abs(testCase.testFilename)
require.NoError(t, err)
args := []string{filename, "--archive-out", tmpPath}
testState := newGlobalTestState(t)
require.NoError(t, afero.WriteFile(testState.fs, filepath.Join(testState.cwd, testCase.testFilename), testScript, 0o644))
testState.args = []string{"k6", "archive", testCase.testFilename}
if testCase.noThresholds {
args = append(args, "--no-thresholds")
testState.args = append(testState.args, "--no-thresholds")
}
cmd.SetArgs(args)
wantExitCode := exitcodes.InvalidConfig

var gotErrExt errext.HasExitCode
gotErr := cmd.Execute()
gotErr := newRootCommand(testState.globalState).cmd.Execute()

assert.Equal(t,
testCase.wantErr,
Expand All @@ -68,9 +60,10 @@ func TestArchiveThresholds(t *testing.T) {
)

if testCase.wantErr {
var gotErrExt errext.HasExitCode
require.ErrorAs(t, gotErr, &gotErrExt)
assert.Equalf(t, wantExitCode, gotErrExt.ExitCode(),
"status code must be %d", wantExitCode,
assert.Equalf(t, exitcodes.InvalidConfig, gotErrExt.ExitCode(),
"status code must be %d", exitcodes.InvalidConfig,
)
}
})
Expand Down
Loading

0 comments on commit c090d0c

Please sign in to comment.