Skip to content

Commit

Permalink
Add some test coverage for Config
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinmcconnell committed Feb 28, 2024
1 parent 220f28d commit 8c83798
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
43 changes: 43 additions & 0 deletions internal/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package internal

import (
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestConfig_defaults(t *testing.T) {
usingProgramArgs(t, "thruster", "echo", "hello")

c, err := NewConfig()
require.NoError(t, err)

assert.Equal(t, 3000, c.TargetPort)
assert.Equal(t, "echo", c.UpstreamCommand)
assert.Equal(t, defaultCacheSize, c.CacheSizeBytes)
}

func TestConfig_override_defaults_with_env_vars(t *testing.T) {
usingProgramArgs(t, "thruster", "echo", "hello")
usingEnvVar(t, "TARGET_PORT", "4000")
usingEnvVar(t, "CACHE_SIZE", "256")
usingEnvVar(t, "HTTP_READ_TIMEOUT", "30")
usingEnvVar(t, "X_SENDFILE_ENABLED", "0")

c, err := NewConfig()
require.NoError(t, err)

assert.Equal(t, 4000, c.TargetPort)
assert.Equal(t, 256, c.CacheSizeBytes)
assert.Equal(t, 30*time.Second, c.HttpReadTimeout)
assert.Equal(t, false, c.XSendfileEnabled)
}

func TestConfig_return_error_when_no_upstream_command(t *testing.T) {
usingProgramArgs(t, "thruster")

_, err := NewConfig()
require.Error(t, err)
}
23 changes: 23 additions & 0 deletions internal/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package internal
import (
"os"
"path"
"testing"
)

func fixturePath(name string) string {
Expand All @@ -18,3 +19,25 @@ func fixtureLength(name string) int64 {
info, _ := os.Stat(fixturePath(name))
return info.Size()
}

func usingEnvVar(t *testing.T, key, value string) {
old, found := os.LookupEnv(key)
os.Setenv(key, value)

t.Cleanup(func() {
if found {
os.Setenv(key, old)
} else {
os.Unsetenv(key)
}
})
}

func usingProgramArgs(t *testing.T, args ...string) {
old := os.Args
os.Args = args

t.Cleanup(func() {
os.Args = old
})
}

0 comments on commit 8c83798

Please sign in to comment.