Skip to content

Commit

Permalink
Merge pull request #5 from dcos/julferts/NewClient
Browse files Browse the repository at this point in the history
added NewClient and default init
  • Loading branch information
mrnugget authored Feb 28, 2019
2 parents 7aade17 + c4604ec commit 1346326
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 36 deletions.
42 changes: 36 additions & 6 deletions dcos/client.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,46 @@
package dcos

import "net/http"
import (
"fmt"
"net/http"
)

// Client
type Client struct {
HttpClient *http.Client
HTTPClient *http.Client
Config *Config
UserAgent string
}

// NewClient returns a Client which will detect its Config through the well
// known process and use a default http.Client with DC/OS authentication.
func NewClient() (*Client, error) {
config, err := NewConfigManager(nil).Current()
if err != nil {
return nil, err
}

httpClient, err := NewHTTPClient(config)
if err != nil {
return nil, err
}

baseURL string
return NewClientWithOptions(httpClient, config)
}

func NewClient(httpClient *http.Client) (*Client, error) {
// NewClientWithOptions creates a Client from a given *http.Client and *Config
func NewClientWithOptions(httpClient *http.Client, config *Config) (*Client, error) {
if httpClient == nil {
httpClient = http.DefaultClient
return nil, fmt.Errorf("httpClient cannot be nil")
}

if config == nil {
return nil, fmt.Errorf("config cannot be nil")
}
return &Client{HttpClient: httpClient}, nil

return &Client{
HTTPClient: httpClient,
Config: config,
UserAgent: fmt.Sprintf("%s(%s)", ClientName, Version),
}, nil
}
56 changes: 35 additions & 21 deletions dcos/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,42 @@ package dcos

import (
"net/http"
"os"
"path/filepath"
"testing"
"time"

homedir "github.com/mitchellh/go-homedir"
"github.com/stretchr/testify/require"
)

func TestClientNew(t *testing.T) {
baseClient := &http.Client{}
c, err := NewClient(baseClient)
if err != nil {
t.Fatalf("NewClient returned unexpected error: %s", err)
}

if c.HttpClient != baseClient {
t.Errorf("client.HttpClient wrong. got=%+v, want=%+v",
c.HttpClient, baseClient)
}

c, err = NewClient(nil)
if err != nil {
t.Fatalf("NewClient returned unexpected error: %s", err)
}

if c.HttpClient != http.DefaultClient {
t.Errorf("client.HttpClient not http.Defaultclient. got=%+v",
c.HttpClient)
}
func TestNewClient(t *testing.T) {
homedir.DisableCache = true
wd, err := os.Getwd()
require.NoError(t, err)
testdir := filepath.Join(wd, "testdata", "config", "single_config_attached")
os.Setenv("HOME", testdir)

c, err := NewClient()

require.NoErrorf(t, err, "NewClient returned unexpected error: %s - testdir: %s", err, testdir)
require.Equal(t, "single_config_attached", c.Config.Name())
require.IsTypef(t, &DefaultTransport{}, c.HTTPClient.Transport, "HTTPClient.Transport type different")
}

func TestNewClientWithOptions(t *testing.T) {
timeout := 7 * time.Second
baseClient := &http.Client{Timeout: timeout}
config := NewConfig(nil)
config.SetACSToken("test")
c, err := NewClientWithOptions(baseClient, config)

require.NoErrorf(t, err, "NewClientWithOptions returned unexpected error: %s", err)
require.Equal(t, baseClient, c.HTTPClient, "NewClientWithOptions should leave HTTPClient unchanged")

_, err = NewClientWithOptions(nil, config)
require.Error(t, err)

_, err = NewClientWithOptions(baseClient, nil)
require.Error(t, err)
}
14 changes: 14 additions & 0 deletions dcos/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"strings"
"time"

homedir "github.com/mitchellh/go-homedir"
toml "github.com/pelletier/go-toml"
"github.com/spf13/afero"
"github.com/spf13/cast"
Expand All @@ -30,6 +31,7 @@ const (
configKeyMesosMasterURL = "core.mesos_master_url"
configKeyPromptLogin = "core.prompt_login"
configKeyClusterName = "cluster.name"
dcosDefaultFolder = "~/.dcos"
)

// Environment variables for the DC/OS configuration.
Expand Down Expand Up @@ -445,6 +447,14 @@ type ConfigManagerOpts struct {
Dir string
}

func expandHomeDir() string {
dir, err := homedir.Expand(dcosDefaultFolder)
if err != nil {
return dcosDefaultFolder
}
return dir
}

// ConfigManager is able to retrieve, create, and delete configs.
type ConfigManager struct {
fs afero.Fs
Expand All @@ -466,6 +476,10 @@ func NewConfigManager(opts *ConfigManagerOpts) *ConfigManager {
opts.EnvLookup = os.LookupEnv
}

if opts.Dir == "" {
opts.Dir = expandHomeDir()
}

return &ConfigManager{
fs: opts.Fs,
dir: opts.Dir,
Expand Down
11 changes: 10 additions & 1 deletion dcos/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import (
"testing"
"time"

"github.com/pelletier/go-toml"
homedir "github.com/mitchellh/go-homedir"
toml "github.com/pelletier/go-toml"
"github.com/spf13/afero"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -533,3 +534,11 @@ func TestConfigAttach(t *testing.T) {
require.NoError(t, manager.Attach(conf))
require.True(t, manager.fileExists(attachedFilePath))
}

func TestExpandHomedir(t *testing.T) {
homedir.DisableCache = true
os.Setenv("HOME", "/home/testuser")
dir := expandHomeDir()

require.Equal(t, dir, "/home/testuser/.dcos", "wrong return")
}
7 changes: 5 additions & 2 deletions dcos/httpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@ func cloneRequest(req *http.Request) *http.Request {
}

// NewHTTPClient provides a http.Client able to communicate to dcos in an authenticated way
func NewHTTPClient(config *Config) *http.Client {
func NewHTTPClient(config *Config) (*http.Client, error) {
if config == nil {
return nil, fmt.Errorf("Config should not be nil")
}
client := &http.Client{}
client.Transport = &http.Transport{

Expand All @@ -76,7 +79,7 @@ func NewHTTPClient(config *Config) *http.Client {
MaxIdleConnsPerHost: DefaultHTTPClientMaxIdleConnsPerHost,
}

return AddTransportHTTPClient(client, config)
return AddTransportHTTPClient(client, config), nil
}

// AddTransportHTTPClient adds dcos.DefaultTransport to http.Client to add dcos authentication
Expand Down
17 changes: 11 additions & 6 deletions dcos/httpclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"

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

func TestDefaultTransportBaseNil(t *testing.T) {
Expand All @@ -23,7 +24,7 @@ func TestDefaultTransportBase(t *testing.T) {
}
rt := c.base()

assert.IsType(t, &DefaultTransport{}, rt)
require.IsType(t, &DefaultTransport{}, rt)
}

func TestDefaultHTTPClientAuth(t *testing.T) {
Expand All @@ -42,13 +43,17 @@ func TestDefaultHTTPClientAuth(t *testing.T) {
}))
defer s.Close()

c := NewHTTPClient(config)
_, err := NewHTTPClient(nil)
require.Error(t, err)

c, err := NewHTTPClient(config)
require.NoError(t, err)

resp, err := c.Get(s.URL)
assert.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode, "using the dcos.NewHTTPClient should respond with 200")
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode, "using the dcos.NewHTTPClient should respond with 200")

respDflt, err := http.DefaultClient.Get(s.URL)
assert.NoError(t, err)
assert.Equal(t, 401, respDflt.StatusCode, "expect a forbidden state with http.DefaultClient")
require.NoError(t, err)
require.Equal(t, 401, respDflt.StatusCode, "expect a forbidden state with http.DefaultClient")
}

0 comments on commit 1346326

Please sign in to comment.