Skip to content

Commit

Permalink
Merge pull request #82 from SimonBaeumer/read-environment-variables
Browse files Browse the repository at this point in the history
Read environment variables
  • Loading branch information
SimonBaeumer authored Sep 4, 2019
2 parents bf885ad + e778856 commit 93f45e1
Show file tree
Hide file tree
Showing 11 changed files with 138 additions and 50 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# v1.2.0

- Add `interval` option for `retries` which allows to execute a retry after a given period of time. I.e. `interval: 50ms`
- Add reading envrionment variables from shell
- Add `interval` option for `retries` which allows to execute a retry after a given period of time. I.e. `interval: 50ms`

# v1.1.0

Expand Down
96 changes: 49 additions & 47 deletions cmd/commander/commander.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,32 +36,13 @@ func createCliApp() *cli.App {
cliapp.Version = version

cliapp.Commands = []cli.Command{
createTestCommand(),
createAddCommand(),
{
Name: "add",
Usage: "Automatically add a test to your test suite",
ArgsUsage: "[command]",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "stdout",
Usage: "Output test file to stdout",
},
cli.BoolFlag{
Name: "no-file",
Usage: "Don't create a commander.yaml",
},
cli.StringFlag{
Name: "file",
Usage: "Write to another file, default is commander.yaml",
},
},
Action: addCommand,
},
}
return cliapp
}

func createAddCommand() cli.Command {
func createTestCommand() cli.Command {
return cli.Command{
Name: "test",
Usage: "Execute the test suite",
Expand Down Expand Up @@ -89,35 +70,56 @@ func createAddCommand() cli.Command {
}
}

func addCommand(c *cli.Context) error {
file := ""
var existedContent []byte
func createAddCommand() cli.Command {
return cli.Command{
Name: "add",
Usage: "Automatically add a test to your test suite",
ArgsUsage: "[command]",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "stdout",
Usage: "Output test file to stdout",
},
cli.BoolFlag{
Name: "no-file",
Usage: "Don't create a commander.yaml",
},
cli.StringFlag{
Name: "file",
Usage: "Write to another file, default is commander.yaml",
},
},
Action: func(c *cli.Context) error {
file := ""
var existedContent []byte

if !c.Bool("no-file") {
dir, _ := os.Getwd()
file = path.Join(dir, app.CommanderFile)
if c.String("file") != "" {
file = c.String("file")
}
existedContent, _ = ioutil.ReadFile(file)
}
if !c.Bool("no-file") {
dir, _ := os.Getwd()
file = path.Join(dir, app.CommanderFile)
if c.String("file") != "" {
file = c.String("file")
}
existedContent, _ = ioutil.ReadFile(file)
}

content, err := app.AddCommand(strings.Join(c.Args(), " "), existedContent)
content, err := app.AddCommand(strings.Join(c.Args(), " "), existedContent)

if err != nil {
return err
}
if err != nil {
return err
}

if c.Bool("stdout") {
fmt.Println(string(content))
}
if !c.Bool("no-file") {
fmt.Println("written to", file)
err := ioutil.WriteFile(file, content, 0755)
if err != nil {
return err
}
}
if c.Bool("stdout") {
fmt.Println(string(content))
}
if !c.Bool("no-file") {
fmt.Println("written to", file)
err := ioutil.WriteFile(file, content, 0755)
if err != nil {
return err
}
}

return nil
return nil
},
}
}
4 changes: 4 additions & 0 deletions commander_unix.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,14 @@ tests:

test global and local configurations:
command: ./commander test ./integration/unix/config_test.yaml
config:
env:
COMMANDER_FROM_SHELL: from_shell
stdout:
contains:
- ✓ should print global env value
- ✓ should print local env value
- ✓ should print env var from shell
exit-code: 0

test add command:
Expand Down
5 changes: 4 additions & 1 deletion commander_windows.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ tests:

test global and local configurations:
command: commander.exe test ./integration/windows/config_test.yaml
config:
env:
COMMANDER_FROM_SHELL: from_shell
stdout:
contains:
- should print global
Expand All @@ -55,4 +58,4 @@ tests:
stdout:
contains:
- ✗ echo hello, retries 3
exit-code: 1
exit-code: 1
1 change: 1 addition & 0 deletions docs/manual.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ config: # Config for all tests
dir: /tmp #Set working directory
env: # Environment variables
KEY: global
PATH_FROM_SHELL: ${PATH} # Read an env variable from the current shell
timeout: 5000 # Timeout in ms
retries: 2 # Define retries for each test

Expand Down
6 changes: 6 additions & 0 deletions integration/unix/config_test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ config:
env:
KEY: value
ANOTHER: global
COMMANDER_FROM_SHELL: ${COMMANDER_FROM_SHELL}
tests:
should print global env value:
command: echo $KEY
Expand All @@ -27,4 +28,9 @@ tests:
command: echo hello
config:
timeout: 100ms
exit-code: 0

should print env var from shell:
command: echo read ${COMMANDER_FROM_SHELL} $KEY
stdout: read from_shell value
exit-code: 0
1 change: 1 addition & 0 deletions integration/windows/config_test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ config:
env:
KEY: value
ANOTHER: global
COMMANDER_FROM_SHELL: ${COMMANDER_FROM_SHELL}
tests:
should print global env value:
command: echo %KEY%
Expand Down
3 changes: 3 additions & 0 deletions integration/windows/shell_env.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
tests:
it should read from shell env:
env:
22 changes: 22 additions & 0 deletions pkg/cmd/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ package cmd
import (
"bytes"
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"syscall"
"time"
)
Expand Down Expand Up @@ -31,10 +34,29 @@ func NewCommand(cmd string) *Command {
}

// AddEnv adds an environment variable to the command
// If a variable gets passed like ${VAR_NAME} the env variable will be read out by the current shell
func (c *Command) AddEnv(key string, value string) {
vars := parseEnvVariableFromShell(value)
for _, v := range vars {
value = strings.Replace(value, v, os.Getenv(removeEnvVarSyntax(v)), -1)
}

c.Env = append(c.Env, fmt.Sprintf("%s=%s", key, value))
}

// Removes the ${...} characters
func removeEnvVarSyntax(v string) string {
return v[2:(len(v) - 1)]
}

//Read all environment variables from the given value
//with the syntax ${VAR_NAME}
func parseEnvVariableFromShell(val string) []string {
reg := regexp.MustCompile(`\$\{.*?\}`)
matches := reg.FindAllString(val, -1)
return matches
}

//SetTimeoutMS sets the timeout in milliseconds
func (c *Command) SetTimeoutMS(ms int) {
if ms == 0 {
Expand Down
43 changes: 43 additions & 0 deletions pkg/cmd/command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd
import (
"fmt"
"github.com/stretchr/testify/assert"
"os"
"runtime"
"testing"
"time"
Expand Down Expand Up @@ -64,6 +65,48 @@ func TestCommand_AddEnv(t *testing.T) {
assert.Equal(t, []string{"key=value"}, c.Env)
}

func TestCommand_AddEnvWithShellVariable(t *testing.T) {
const TestEnvKey = "COMMANDER_TEST_SOME_KEY"
os.Setenv(TestEnvKey, "test from shell")
defer os.Unsetenv(TestEnvKey)

c := NewCommand(getCommand())
c.AddEnv("SOME_KEY", fmt.Sprintf("${%s}", TestEnvKey))

err := c.Execute()

assert.Nil(t, err)
assert.Equal(t, "test from shell", c.Stdout())
}

func TestCommand_AddMultipleEnvWithShellVariable(t *testing.T) {
const TestEnvKeyPlanet = "COMMANDER_TEST_PLANET"
const TestEnvKeyName = "COMMANDER_TEST_NAME"
os.Setenv(TestEnvKeyPlanet, "world")
os.Setenv(TestEnvKeyName, "Simon")
defer func() {
os.Unsetenv(TestEnvKeyPlanet)
os.Unsetenv(TestEnvKeyName)
}()

c := NewCommand(getCommand())
envValue := fmt.Sprintf("Hello ${%s}, I am ${%s}", TestEnvKeyPlanet, TestEnvKeyName)
c.AddEnv("SOME_KEY", envValue)

err := c.Execute()

assert.Nil(t, err)
assert.Equal(t, "Hello world, I am Simon", c.Stdout())
}

func getCommand() string {
command := "echo $SOME_KEY"
if runtime.GOOS == "windows" {
command = "echo %SOME_KEY%"
}
return command
}

func TestCommand_SetTimeoutMS_DefaultTimeout(t *testing.T) {
c := NewCommand("echo test")
c.SetTimeoutMS(0)
Expand Down
4 changes: 3 additions & 1 deletion pkg/runtime/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ const (
LineCount = "LineCount"
)

const WorkerCountMultiplicator = 5

// Result status codes
const (
//Success status
Expand Down Expand Up @@ -108,7 +110,7 @@ func Start(tests []TestCase, maxConcurrent int) <-chan TestResult {

workerCount := maxConcurrent
if maxConcurrent == 0 {
workerCount = runtime.NumCPU() * 5
workerCount = runtime.NumCPU() * WorkerCountMultiplicator
}

var wg sync.WaitGroup
Expand Down

0 comments on commit 93f45e1

Please sign in to comment.