Skip to content

Commit

Permalink
add: introduce afero and test getOAuthConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
nasa9084 committed May 7, 2020
1 parent 0739a6b commit dfd51b8
Show file tree
Hide file tree
Showing 5 changed files with 133 additions and 6 deletions.
1 change: 1 addition & 0 deletions commands/main.go → commands/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"path/filepath"

"github.com/jessevdk/go-flags"

"github.com/nasa9084/gmac/log"
)

Expand Down
16 changes: 10 additions & 6 deletions commands/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"path/filepath"
"runtime"

"github.com/spf13/afero"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/gmail/v1"
Expand All @@ -22,6 +23,9 @@ var oauthScope = []string{
gmail.GmailSettingsBasicScope,
}

var fs = afero.NewOsFs()
var stdin io.Reader = os.Stdin

type raw []byte

func (r *raw) UnmarshalYAML(data []byte) error {
Expand All @@ -39,10 +43,10 @@ func getOAuthConfig(credentialsFilepath string) (*oauth2.Config, error) {
switch credentialsFilepath {
case "-": // read from stdin
log.Vprint("read OAuth config from stdin")
r = os.Stdin
r = stdin
case "": // read from default config path
log.Vprintf("read OAuth config from %s", defaultCredentialsFilepath)
f, err := os.Open(defaultCredentialsFilepath)
f, err := fs.Open(defaultCredentialsFilepath)
if err != nil {
return nil, err
}
Expand All @@ -51,7 +55,7 @@ func getOAuthConfig(credentialsFilepath string) (*oauth2.Config, error) {
r = f
default: // read from specified filepath
log.Vprintf("read OAuthconfig from %s", credentialsFilepath)
f, err := os.Open(credentialsFilepath)
f, err := fs.Open(credentialsFilepath)
if err != nil {
return nil, err
}
Expand All @@ -69,9 +73,9 @@ func getOAuthConfig(credentialsFilepath string) (*oauth2.Config, error) {
}
if credentialsFilepath != "" {
log.Vprint("OAuth config is not read from config directory: save into config directory")
if err := os.MkdirAll(configDir, 0755); err != nil {
if err := fs.MkdirAll(configDir, 0755); err != nil {
log.Printf("WARN: cannot create config directory: %s", configDir)
} else if err := ioutil.WriteFile(defaultCredentialsFilepath, b, 0644); err != nil {
} else if err := afero.WriteFile(fs, defaultCredentialsFilepath, b, 0644); err != nil {
log.Printf("WARN: %+v", err)
}
}
Expand All @@ -87,7 +91,7 @@ func getToken(refreshToken string) (*oauth2.Token, error) {
}
tokenFilepath := filepath.Join(configDir, "token.json")
log.Vprintf("refresh token is not passed, read OAuth token from %s", tokenFilepath)
b, err := ioutil.ReadFile(tokenFilepath)
b, err := afero.ReadFile(fs, tokenFilepath)
if err != nil {
return nil, err
}
Expand Down
119 changes: 119 additions & 0 deletions commands/util_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package commands

import (
"bytes"
"fmt"
"os"
"path/filepath"
"testing"

"github.com/spf13/afero"
)

func TestGetOAuthConfig(t *testing.T) {
const credFileTmpl = `{
"installed":{
"client_id":"%s",
"project_id":"projectID",
"auth_uri":"https://example.com/auth",
"token_uri":"https://example.com/token",
"auth_provider_x509_cert_url":"https://example.com/oauth2/v1/certs",
"client_secret":"clientSecret",
"redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]
}
}`
setupFs := func() func() {
fs = afero.NewMemMapFs()
return func() {
fs = afero.NewOsFs()
}
}

t.Run("from stdin", func(t *testing.T) {
teardownFs := setupFs()
defer teardownFs()

clientID := "stdin"

// setup standard input
var buf bytes.Buffer
fmt.Fprintf(&buf, credFileTmpl, clientID)
stdin = &buf
defer func() { stdin = os.Stdin }()

// call with "-" means "read from stdin"
cfg, err := getOAuthConfig("-")
if err != nil {
t.Fatal(err)
}

if cfg.ClientID != clientID {
t.Errorf("client id is unexpected value: %s != %s", cfg.ClientID, clientID)
return
}

// check copied credentials.json
b, err := afero.ReadFile(fs, filepath.Join(configDir, "credentials.json"))
if err != nil {
t.Error(err)
}
if fmt.Sprintf(credFileTmpl, clientID) != string(b) {
t.Errorf("credential.json should be copied in config directory, but unexpected contents")
return
}
})

t.Run("from default path", func(t *testing.T) {
teardownFs := setupFs()
defer teardownFs()

clientID := "default"

// setup credentials.json in config dir
fs.MkdirAll(configDir, 0755)
afero.WriteFile(fs, filepath.Join(configDir, "credentials.json"), []byte(fmt.Sprintf(credFileTmpl, clientID)), 0644)

// call with empty string means "read from config dir"
cfg, err := getOAuthConfig("")
if err != nil {
t.Fatal(err)
}

if cfg.ClientID != clientID {
t.Errorf("client id is unexpected value: %s != %s", cfg.ClientID, clientID)
return
}
})

t.Run("from specified path", func(t *testing.T) {
teardownFs := setupFs()
defer teardownFs()

clientID := "tmp"
credentialsFilepath := filepath.Join("/", "tmp", "credentials.json")

// setup credentials.json in /tmp
fs.Mkdir("tmp", 0755)
afero.WriteFile(fs, credentialsFilepath, []byte(fmt.Sprintf(credFileTmpl, clientID)), 0644)

cfg, err := getOAuthConfig(credentialsFilepath)
if err != nil {
t.Fatal(err)
}

if cfg.ClientID != clientID {
t.Errorf("client id is unexpected value: %s != %s", cfg.ClientID, clientID)
return
}

// check copied credentials.json
b, err := afero.ReadFile(fs, filepath.Join(configDir, "credentials.json"))
if err != nil {
t.Error(err)
}
if fmt.Sprintf(credFileTmpl, clientID) != string(b) {
t.Errorf("credential.json should be copied in config directory, but unexpected contents")
return
}
})
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/golang/protobuf v1.4.0 // indirect
github.com/google/uuid v1.1.1
github.com/jessevdk/go-flags v1.4.0
github.com/spf13/afero v1.2.2
golang.org/x/net v0.0.0-20200425230154-ff2c4b7c35a0 // indirect
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
golang.org/x/sys v0.0.0-20200427175716-29b57079015a // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc=
github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
Expand Down

0 comments on commit dfd51b8

Please sign in to comment.