Skip to content

Commit

Permalink
Merge pull request #85 from drmdrew/no-vault-addr-dont-panic
Browse files Browse the repository at this point in the history
No vault addr dont panic
  • Loading branch information
hairyhenderson authored Nov 22, 2016
2 parents 3933b35 + 456eebd commit d12a938
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
13 changes: 11 additions & 2 deletions vault/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import (
"time"
)

// logFatal is defined so log.Fatal calls can be overridden for testing
var logFatal = log.Fatal

// Client -
type Client struct {
Addr *url.URL
Expand All @@ -37,9 +40,14 @@ func NewClient() *Client {

func getVaultAddr() *url.URL {
vu := os.Getenv("VAULT_ADDR")
if vu == "" {
logFatal("VAULT_ADDR is an unparseable URL!")
return nil
}
u, err := url.Parse(vu)
if err != nil {
log.Fatal("VAULT_ADDR is an unparseable URL!", err)
logFatal("VAULT_ADDR is an unparseable URL!", err)
return nil
}
return u
}
Expand All @@ -51,6 +59,7 @@ func getAuthStrategy() AuthStrategy {
if auth := NewTokenAuthStrategy(); auth != nil {
return auth
}
logFatal("No vault auth strategy configured")
return nil
}

Expand Down Expand Up @@ -83,7 +92,7 @@ func (c *Client) Do(req *http.Request) (*http.Response, error) {
func (c *Client) Login() error {
token, err := c.Auth.GetToken(c.Addr)
if err != nil {
log.Fatal(err)
logFatal(err)
return err
}
c.token = token
Expand Down
36 changes: 36 additions & 0 deletions vault/client_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,48 @@
package vault

import (
"log"
"net/url"
"os"
"testing"

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

var spyLogFatalMsg string

func restoreLogFatal() {
logFatal = log.Fatal
}

func mockLogFatal(args ...interface{}) {
spyLogFatalMsg = (args[0]).(string)
}

func setupMockLogFatal() {
logFatal = mockLogFatal
spyLogFatalMsg = ""
}
func TestNewClient_NoVaultAddr(t *testing.T) {
os.Unsetenv("VAULT_ADDR")
defer restoreLogFatal()
setupMockLogFatal()
c := NewClient()
assert.Nil(t, c.Addr)
assert.Equal(t, "VAULT_ADDR is an unparseable URL!", spyLogFatalMsg)
}

func TestLogin_NoAuthStrategy(t *testing.T) {
os.Setenv("VAULT_ADDR", "https://localhost:8500")
os.Unsetenv("VAULT_APP_ID")
os.Unsetenv("VAULT_USER_ID")
os.Setenv("HOME", "/tmp")
defer restoreLogFatal()
setupMockLogFatal()
_ = NewClient()
assert.Equal(t, "No vault auth strategy configured", spyLogFatalMsg)
}

func TestLogin_SavesToken(t *testing.T) {
auth := &TokenAuthStrategy{"foo"}
client := &Client{
Expand Down

0 comments on commit d12a938

Please sign in to comment.