Skip to content

Commit

Permalink
test: improve test coverage (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
wass3r authored Jan 18, 2021
1 parent a9c0b28 commit efb364d
Show file tree
Hide file tree
Showing 10 changed files with 284 additions and 25 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ require (
github.com/coreos/go-semver v0.3.0
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gin-gonic/gin v1.6.3
github.com/go-vela/mock v0.7.0-rc1
github.com/go-vela/mock v0.7.0-rc1.0.20210115203827-902c57d55bd5
github.com/go-vela/types v0.7.0-rc1
github.com/google/go-querystring v1.0.0
github.com/sirupsen/logrus v1.7.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
github.com/go-vela/mock v0.7.0-rc1 h1:Rhb5XWYNxAlL0Nus9CEwrlWx4xOQTwKImKt0xc4i8Rs=
github.com/go-vela/mock v0.7.0-rc1/go.mod h1:diiACzMDRowQH/ayauz7c7YSRsqOHwaoC8V0rgO3qIs=
github.com/go-vela/mock v0.7.0-rc1.0.20210115203827-902c57d55bd5 h1:oqoOFn3wAuh4QvxxzcdUiWxoBXENrYRhvskbQa2jmjY=
github.com/go-vela/mock v0.7.0-rc1.0.20210115203827-902c57d55bd5/go.mod h1:diiACzMDRowQH/ayauz7c7YSRsqOHwaoC8V0rgO3qIs=
github.com/go-vela/types v0.7.0-rc1 h1:Q16xpyfLD3uc20mDimidjQoSwi7HG7ukfYJs74I/XHY=
github.com/go-vela/types v0.7.0-rc1/go.mod h1:ATtwTwp2l4jI4GUmw840xHZgHmg8FbZPo4g0azImggA=
github.com/goccy/go-yaml v1.8.4 h1:AOEdR7aQgbgwHznGe3BLkDQVujxCPUpHOZZcQcp8Y3M=
Expand Down
13 changes: 5 additions & 8 deletions vela/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func (svc *AuthenticationService) HasAccessAndRefreshAuth() bool {

// RefreshAccessToken uses the supplied refresh token to attempt and refresh
// the access token.
func (svc *AuthenticationService) RefreshAccessToken(refreshToken string) error {
func (svc *AuthenticationService) RefreshAccessToken(refreshToken string) (*Response, error) {
u := "/token-refresh"

v := new(library.Login)
Expand All @@ -70,12 +70,12 @@ func (svc *AuthenticationService) RefreshAccessToken(refreshToken string) error
// that's what can send us here
url, err := svc.client.buildURLForRequest(u)
if err != nil {
return err
return nil, err
}

req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
return nil, err
}

// set a minimal cookie with the refresh token value
Expand All @@ -87,13 +87,10 @@ func (svc *AuthenticationService) RefreshAccessToken(refreshToken string) error
req.AddCookie(cookie)

// send the request
_, err = svc.client.Do(req, v)
if err != nil {
return err
}
resp, err := svc.client.Do(req, v)

// set the received access token
svc.accessToken = v.Token

return nil
return resp, err
}
51 changes: 51 additions & 0 deletions vela/authentication_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@
package vela

import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"

"github.com/gin-gonic/gin"
"github.com/go-vela/mock/server"
"github.com/go-vela/types/library"
)

func TestVela_Authentication_SetTokenAuth(t *testing.T) {
Expand All @@ -23,3 +30,47 @@ func TestVela_Authentication_SetTokenAuth(t *testing.T) {
t.Errorf("SetTokenAuth did not set AuthenticationToken type")
}
}

func TestVela_Authentication_SetAccessAndRefreshAuth(t *testing.T) {
// setup types
c, _ := NewClient("http://localhost:8080", "", nil)

// run test
c.Authentication.SetAccessAndRefreshAuth("someAccessToken", "someRefreshToken")

if !c.Authentication.HasAuth() {
t.Errorf("SetAccessAndRefreshAuth did not set an authentication type")
}

if !c.Authentication.HasAccessAndRefreshAuth() {
t.Errorf("SetAccessAndRefreshAuth did not set AccessAndRefreshToken type")
}
}

func TestVela_Authentication_RefreshAccessToken(t *testing.T) {
// setup context
gin.SetMode(gin.TestMode)

s := httptest.NewServer(server.FakeHandler())
c, _ := NewClient(s.URL, "", nil)

data := []byte(server.TokenRefreshResp)

var want library.Login
_ = json.Unmarshal(data, &want)

// run test
resp, err := c.Authentication.RefreshAccessToken("refreshToken")

if err != nil {
t.Errorf("New returned err: %v", err)
}

if resp.StatusCode != http.StatusOK {
t.Errorf("RefreshAccessToken returned %v, want %v", resp.StatusCode, http.StatusOK)
}

if *c.Authentication.accessToken != want.GetToken() {
t.Errorf("RefreshAccessToken didn't return token")
}
}
3 changes: 2 additions & 1 deletion vela/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func (c *Client) addAuthentication(req *http.Request) error {

logrus.Debug("fetching new access token with existing refresh token")

err := c.Authentication.RefreshAccessToken(*c.Authentication.refreshToken)
_, err := c.Authentication.RefreshAccessToken(*c.Authentication.refreshToken)
if err != nil {
return err
}
Expand Down Expand Up @@ -299,6 +299,7 @@ func (r *Response) populatePageValues() {
segments := strings.Split(strings.TrimSpace(link), ";")

// link must at least have href and rel
// nolint: gomnd // ignoring magic number
if len(segments) < 2 {
continue
}
Expand Down
108 changes: 107 additions & 1 deletion vela/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ package vela
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"testing"

"github.com/go-vela/mock/server"
"github.com/go-vela/sdk-go/version"
)

Expand Down Expand Up @@ -74,6 +76,23 @@ func TestVela_NewClient_EmptyUrl(t *testing.T) {
}
}

func TestVela_NewClient_UserAgent(t *testing.T) {
// setup types
addr := "http://localhost:8080"

want := fmt.Sprintf("%s/%s (%s)", userAgent, version.Version.String(), "vela")

// run test
got, err := NewClient(addr, "vela", nil)
if err != nil {
t.Errorf("NewClient returned err: %v", err)
}

if got.UserAgent != want {
t.Errorf("NewClient is %v, want %v", got, want)
}
}

func TestVela_NewClient_BadUrl(t *testing.T) {
// run test
got, err := NewClient("!@#$%^&*()", "", nil)
Expand Down Expand Up @@ -180,7 +199,94 @@ func TestVela_addAuthentication(t *testing.T) {

// run test
c.Authentication.SetTokenAuth("foobar")
_ = c.addAuthentication(r)

err = c.addAuthentication(r)
if err != nil {
t.Error("addAuthentication should not have errored")
}

got := r.Header.Get("Authorization")

if !reflect.DeepEqual(got, want) {
t.Errorf("addAuthentication is %v, want %v", got, want)
}
}

func TestVela_addAuthentication_AccessAndRefresh_GoodToken(t *testing.T) {
// setup types
testToken := TestTokenGood
want := fmt.Sprintf("Bearer %s", testToken)

c, err := NewClient("http://localhost:8080", "", nil)
if err != nil {
t.Errorf("Unable to create new client: %v", err)
}

r, err := http.NewRequest("GET", "http://localhost:8080/health", nil)
if err != nil {
t.Errorf("Unable to create new request: %v", err)
}

// run test
c.Authentication.SetAccessAndRefreshAuth(testToken, "bar")

err = c.addAuthentication(r)
if err != nil {
t.Error("addAuthentication should not have errored")
}

got := r.Header.Get("Authorization")

if !reflect.DeepEqual(got, want) {
t.Errorf("addAuthentication is %v, want %v", got, want)
}
}

func TestVela_addAuthentication_AccessAndRefresh_ExpiredTokens(t *testing.T) {
// setup types
testToken := TestTokenExpired

c, err := NewClient("http://localhost:8080", "", nil)
if err != nil {
t.Errorf("Unable to create new client: %v", err)
}

r, err := http.NewRequest("GET", "http://localhost:8080/health", nil)
if err != nil {
t.Errorf("Unable to create new request: %v", err)
}

// run test
c.Authentication.SetAccessAndRefreshAuth(testToken, testToken)

err = c.addAuthentication(r)
if err == nil {
t.Error("addAuthentication should have errored with expired tokens")
}
}

func TestVela_addAuthentication_AccessAndRefresh_ExpiredAccessGoodRefresh(t *testing.T) {
// setup types
want := fmt.Sprintf("Bearer header.payload.signature")

s := httptest.NewServer(server.FakeHandler())
c, err := NewClient(s.URL, "", nil)
if err != nil {
t.Errorf("Unable to create new client: %v", err)
}

r, err := http.NewRequest("GET", fmt.Sprintf("%s/health", s.URL), nil)
if err != nil {
t.Errorf("Unable to create new request: %v", err)
}

// run test
c.Authentication.SetAccessAndRefreshAuth(TestTokenExpired, TestTokenGood)

err = c.addAuthentication(r)
if err != nil {
t.Error("addAuthentication should not have errored")
}

got := r.Header.Get("Authorization")

Expand Down
10 changes: 1 addition & 9 deletions vela/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
package vela

import (
"encoding/json"
"time"

jwt "github.com/dgrijalva/jwt-go"
Expand Down Expand Up @@ -41,14 +40,7 @@ func IsTokenExpired(token string) bool {
}

// check the expiration
var expiration time.Time
switch e := c["exp"].(type) {
case float64:
expiration = time.Unix(int64(e), 0)
case json.Number:
v, _ := e.Int64()
expiration = time.Unix(v, 0)
}
expiration := time.Unix(int64(c["exp"].(float64)), 0)

// get the difference
timeLeft := time.Until(expiration)
Expand Down
31 changes: 29 additions & 2 deletions vela/jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@ import (
"github.com/dgrijalva/jwt-go"
)

var (
TestTokenGood = makeSampleToken(jwt.MapClaims{"exp": float64(time.Now().Unix() + 100)})
TestTokenExpired = makeSampleToken(jwt.MapClaims{"exp": float64(time.Now().Unix() - 100)})
)

func TestIsTokenExpired(t *testing.T) {
// run tests
type args struct {
token string
}
Expand All @@ -24,17 +30,38 @@ func TestIsTokenExpired(t *testing.T) {
{
name: "expired token",
args: args{
token: makeSampleToken(jwt.MapClaims{"exp": float64(time.Now().Unix() - 100)}),
token: TestTokenExpired,
},
want: true,
},
{
name: "good token",
args: args{
token: makeSampleToken(jwt.MapClaims{"exp": float64(time.Now().Unix() + 100)}),
token: TestTokenGood,
},
want: false,
},
{
name: "empty token",
args: args{
token: "",
},
want: true,
},
{
name: "bad token",
args: args{
token: "/65",
},
want: true,
},
{
name: "no exp",
args: args{
token: makeSampleToken(jwt.MapClaims{}),
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down
12 changes: 11 additions & 1 deletion vela/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@

package vela

import "github.com/go-vela/types/library"
import (
"fmt"

"github.com/go-vela/types/library"
)

// AuthorizationService handles user login actions
// against the server methods of the Vela API.
type AuthorizationService service

// Login constructs a build with the provided details.
// TODO: repurpose legacy method
func (svc *AuthorizationService) Login(l *library.Login) (*library.Login, *Response, error) {
// set the API endpoint path we send the request to
u := "/login"
Expand Down Expand Up @@ -39,6 +44,11 @@ func (svc *AuthorizationService) GetLoginURL(opt *LoginOpts) (string, error) {
}
}

// check that we have a client
if svc.client == nil {
return "", fmt.Errorf("client not found")
}

// build the url
loginURL, err := svc.client.buildURLForRequest(l)
if err != nil {
Expand Down
Loading

0 comments on commit efb364d

Please sign in to comment.