Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix unit tests #56

Merged
merged 3 commits into from
Dec 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions acls.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,26 @@ type ACL *api.ACL
// GetVolumeACL returns the ACL for a volume.
func (c *Client) GetVolumeACL(
ctx context.Context,
volumeName string) (ACL, error) {

volumeName string,
) (ACL, error) {
return api.ACLInspect(ctx, c.API, volumeName)
}

// SetVolumeOwnerToCurrentUser sets the owner for a volume to the user that
// was used to connect to the API.
func (c *Client) SetVolumeOwnerToCurrentUser(
ctx context.Context,
volumeName string) error {

volumeName string,
) error {
return c.SetVolumeOwner(ctx, volumeName, c.API.User())
}

// SetVolumeOwner sets the owner for a volume.
func (c *Client) SetVolumeOwner(
ctx context.Context,
volumeName, userName string) error {

mode := api.FileMode(0777)
volumeName, userName string,
) error {
mode := api.FileMode(0o777)

return api.ACLUpdate(
ctx,
Expand All @@ -68,8 +68,8 @@ func (c *Client) SetVolumeOwner(
// SetVolumeMode sets the permissions to the specified mode (chmod)
func (c *Client) SetVolumeMode(
ctx context.Context,
volumeName string, mode int) error {

volumeName string, mode int,
) error {
filemode := api.FileMode(mode)

return api.ACLUpdate(
Expand Down
19 changes: 15 additions & 4 deletions acls_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ limitations under the License.
package goisilon

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -34,17 +35,22 @@ func TestGetVolumeACL(t *testing.T) {

defer client.DeleteVolume(defaultCtx, volume.Name)

username := client.API.User()
user, err := client.GetUserByNameOrUID(defaultCtx, &username, nil)
assertNoError(t, err)
assertNotNil(t, user)

acl, err := client.GetVolumeACL(defaultCtx, volume.Name)
assertNoError(t, err)
assertNotNil(t, acl)

assertNotNil(t, acl.Owner)
assertNotNil(t, acl.Owner.Name)
assert.Equal(t, client.API.User(), *acl.Owner.Name)
assert.Equal(t, user.Name, *acl.Owner.Name)
assertNotNil(t, acl.Owner.Type)
assert.Equal(t, api.PersonaTypeUser, *acl.Owner.Type)
assertNotNil(t, acl.Owner.ID)
assert.Equal(t, "10", acl.Owner.ID.ID)
assert.Equal(t, user.OnDiskUserIdentity.Id, fmt.Sprintf("UID:%s", acl.Owner.ID.ID))
assert.Equal(t, api.PersonaIDTypeUID, acl.Owner.ID.Type)
}

Expand All @@ -59,17 +65,22 @@ func TestSetVolumeOwnerToCurrentUser(t *testing.T) {

defer client.DeleteVolume(defaultCtx, volume.Name)

username := client.API.User()
user, err := client.GetUserByNameOrUID(defaultCtx, &username, nil)
assertNoError(t, err)
assertNotNil(t, user)

acl, err := client.GetVolumeACL(defaultCtx, volume.Name)
assertNoError(t, err)
assertNotNil(t, acl)

assertNotNil(t, acl.Owner)
assertNotNil(t, acl.Owner.Name)
assert.Equal(t, client.API.User(), *acl.Owner.Name)
assert.Equal(t, user.Name, *acl.Owner.Name)
assertNotNil(t, acl.Owner.Type)
assert.Equal(t, api.PersonaTypeUser, *acl.Owner.Type)
assertNotNil(t, acl.Owner.ID)
assert.Equal(t, "10", acl.Owner.ID.ID)
assert.Equal(t, user.OnDiskUserIdentity.Id, fmt.Sprintf("UID:%s", acl.Owner.ID.ID))
assert.Equal(t, api.PersonaIDTypeUID, acl.Owner.ID.Type)

err = client.SetVolumeOwner(defaultCtx, volume.Name, "rexray")
Expand Down
38 changes: 18 additions & 20 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
defaultVolumesPathPermissions = "0777"
defaultIgnoreUnresolvableHosts = false
headerISISessToken = "Cookie"
headerISICSRFToken = "X-CSRF-Token"

Check failure on line 49 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

G101: Potential hardcoded credentials (gosec)
headerISIReferer = "Referer"
isiSessCsrfToken = "Set-Cookie"
authTypeBasic = 0
Expand All @@ -60,7 +60,6 @@

// Client is an API client.
type Client interface {

// Do sends an HTTP request to the OneFS API.
Do(
ctx context.Context,
Expand Down Expand Up @@ -168,9 +167,9 @@
type VerboseType uint

const (
Verbose_High VerboseType = 0

Check warning on line 170 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

var-naming: don't use underscores in Go names; const Verbose_High should be VerboseHigh (revive)
Verbose_Medium VerboseType = 1

Check warning on line 171 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

var-naming: don't use underscores in Go names; const Verbose_Medium should be VerboseMedium (revive)
Verbose_Low VerboseType = 2

Check warning on line 172 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

var-naming: don't use underscores in Go names; const Verbose_Low should be VerboseLow (revive)
)

type apiVerResponse struct {
Expand Down Expand Up @@ -214,8 +213,8 @@
ctx context.Context,
hostname, username, password, groupname string,
verboseLogging uint, authType uint8,
opts *ClientOptions) (Client, error) {

opts *ClientOptions,
) (Client, error) {
if hostname == "" || username == "" || password == "" {
return nil, errNewClient
}
Expand Down Expand Up @@ -260,7 +259,7 @@
if opts.Insecure {
c.http.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,

Check failure on line 262 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

G402: TLS InsecureSkipVerify set true. (gosec)
},
}
} else {
Expand All @@ -269,7 +268,7 @@
return nil, err
}
c.http.Transport = &http.Transport{
TLSClientConfig: &tls.Config{

Check failure on line 271 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

G402: TLS MinVersion too low. (gosec)
RootCAs: pool,
InsecureSkipVerify: false,
},
Expand Down Expand Up @@ -318,8 +317,8 @@
ctx context.Context,
path, id string,
params OrderedValues, headers map[string]string,
resp interface{}) error {

resp interface{},
) error {
return c.executeWithRetryAuthenticate(
ctx, http.MethodGet, path, id, params, headers, nil, resp)
}
Expand All @@ -328,8 +327,8 @@
ctx context.Context,
path, id string,
params OrderedValues, headers map[string]string,
body, resp interface{}) error {

body, resp interface{},
) error {
return c.executeWithRetryAuthenticate(
ctx, http.MethodPost, path, id, params, headers, body, resp)
}
Expand All @@ -338,8 +337,8 @@
ctx context.Context,
path, id string,
params OrderedValues, headers map[string]string,
body, resp interface{}) error {

body, resp interface{},
) error {
return c.executeWithRetryAuthenticate(
ctx, http.MethodPut, path, id, params, headers, body, resp)
}
Expand All @@ -348,8 +347,8 @@
ctx context.Context,
path, id string,
params OrderedValues, headers map[string]string,
resp interface{}) error {

resp interface{},
) error {
return c.executeWithRetryAuthenticate(
ctx, http.MethodDelete, path, id, params, headers, nil, resp)
}
Expand All @@ -358,8 +357,8 @@
ctx context.Context,
method, path, id string,
params OrderedValues,
body, resp interface{}) error {

body, resp interface{},
) error {
return c.executeWithRetryAuthenticate(ctx, method, path, id, params, nil, body, resp)
}

Expand All @@ -375,8 +374,8 @@
ctx context.Context,
method, uri, id string,
params OrderedValues, headers map[string]string,
body, resp interface{}) error {

body, resp interface{},
) error {
res, _, err := c.DoAndGetResponseBody(
ctx, method, uri, id, params, headers, body)
if err != nil {
Expand Down Expand Up @@ -412,8 +411,8 @@
ctx context.Context,
method, uri, id string,
params OrderedValues, headers map[string]string,
body interface{}) (*http.Response, bool, error) {

body interface{},
) (*http.Response, bool, error) {
var (
err error
req *http.Request
Expand Down Expand Up @@ -617,10 +616,10 @@
func (c *client) authenticate(ctx context.Context, username string, password string, endpoint string) error {
headers := make(map[string]string, 1)
headers[headerKeyContentType] = headerValContentTypeJSON
var data = &setupConnection{Services: []string{"platform", "namespace"}, Username: username, Password: password}
data := &setupConnection{Services: []string{"platform", "namespace"}, Username: username, Password: password}
resp, _, err := c.DoAndGetResponseBody(ctx, http.MethodPost, "/session/1/session", "", nil, headers, data)
if err != nil {
return errors.New(fmt.Sprintf("Authentication error: %v", err))

Check warning on line 622 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

errorf: should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...) (revive)
}

if resp != nil {
Expand All @@ -639,18 +638,18 @@
case resp.StatusCode == 401:
{
log.Debug(ctx, "Response Code %v", resp)
return errors.New(fmt.Sprintf("Authentication failed. Unable to login to PowerScale. Verify username and password."))

Check warning on line 641 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

errorf: should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...) (revive)
}
default:
return errors.New(fmt.Sprintf("Authenticate error. Response:"))

Check warning on line 644 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

errorf: should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...) (revive)
}

headerRes := strings.Join(resp.Header.Values(isiSessCsrfToken), " ")

startIndex, endIndex, matchStrLen := FetchValueIndexForKey(headerRes, "isisessid=", ";")
if startIndex < 0 || endIndex < 0 {
return errors.New(fmt.Sprintf("Session ID not retrieved"))

Check warning on line 651 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

errorf: should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...) (revive)
} else {

Check warning on line 652 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

indent-error-flow: if block ends with a return statement, so drop this else and outdent its block (revive)
c.SetAuthToken(headerRes[startIndex : startIndex+matchStrLen+endIndex])
}

Expand Down Expand Up @@ -688,7 +687,7 @@
return fmt.Errorf("authentication failure due to: %v", err)
}
return c.DoWithHeaders(ctx, method, uri, id, params, headers, body, resp)
} else {

Check warning on line 690 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

indent-error-flow: if block ends with a return statement, so drop this else and outdent its block (revive)
log.Error(ctx, "Error in response. Method:%s URI:%s Error: %v JSON Error: %+v", method, uri, err, e)
}
} else {
Expand All @@ -699,8 +698,7 @@
}

func FetchValueIndexForKey(l string, match string, sep string) (int, int, int) {

var startIndex, endIndex = -1, -1
startIndex, endIndex := -1, -1
if strings.Contains(l, match) {
startIndex = strings.Index(l, match)
if startIndex != -1 && sep != "" {
Expand Down
15 changes: 8 additions & 7 deletions api/api_logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,19 @@
"context"
"encoding/base64"
"fmt"
log "github.com/akutz/gournal"
"io"
"net/http"
"net/http/httputil"
"strings"

log "github.com/akutz/gournal"
)

func isBinOctetBody(h http.Header) bool {
return h.Get(headerKeyContentType) == headerValContentTypeBinaryOctetStream
}

func logRequest(ctx context.Context, w io.Writer, req *http.Request, verbose VerboseType) {

Check warning on line 36 in api/api_logging.go

View workflow job for this annotation

GitHub Actions / golangci-lint

unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
fmt.Fprintln(w, "")
fmt.Fprint(w, " -------------------------- ")
fmt.Fprint(w, "GOISILON HTTP REQUEST")
Expand All @@ -40,10 +41,10 @@

switch verbose {
case Verbose_Low:
//minimal logging, i.e. print request line only
// minimal logging, i.e. print request line only
fmt.Fprintf(w, " %s %s %s\r\n", req.Method, req.URL.RequestURI(), req.Proto)
default:
//full logging, i.e. print full request message content
// full logging, i.e. print full request message content
buf, _ := httputil.DumpRequest(req, !isBinOctetBody(req.Header))
decodedBuf := encryptPassword(buf)
WriteIndented(w, decodedBuf)
Expand All @@ -63,17 +64,17 @@

switch verbose {
case Verbose_Low:
//minimal logging, i.e. pirnt status line only
// minimal logging, i.e. pirnt status line only
fmt.Fprintf(w, " %s %s\r\n", res.Proto, res.Status)
case Verbose_Medium:
//print status line + headers
// print status line + headers
buf, _ = httputil.DumpResponse(res, false)
default:
//print full response message content
// print full response message content
buf, _ = httputil.DumpResponse(res, !isBinOctetBody(res.Header))
}

//when DumpResponse gets err, buf will be nil. No message content will be printed
// when DumpResponse gets err, buf will be nil. No message content will be printed
WriteIndented(w, buf)

log.Debug(ctx, w.String())
Expand Down
1 change: 0 additions & 1 deletion api/api_ordered_values.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,6 @@ var hexChars = []byte{
}

func escapeTo(w io.Writer, s []byte) error {

var (
hexCount = 0
spaceCount = 0
Expand Down
6 changes: 3 additions & 3 deletions api/api_ordered_values_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,9 +223,9 @@ func TestParseQuery(t *testing.T) {

func TestStructToOrderedValues(t *testing.T) {
type TestStruct struct {
TestString *string `json:"test_string,omitempty"`
TestInt *int `json:"test_int,omitempty"`
TestBool *bool `json:"test_bool,omitempty"`
TestString *string `json:"test_string,omitempty"`
TestInt *int `json:"test_int,omitempty"`
TestBool *bool `json:"test_bool,omitempty"`
IgnoredField string
}
testString := "A"
Expand Down
6 changes: 4 additions & 2 deletions api/common/utils/poll.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ import (

var ErrWaitTimeout = errors.New("timed out waiting for the condition")

type WaitWithContextFunc func(ctx context.Context) <-chan struct{}
type ConditionWithContextFunc func(context.Context) (done bool, err error)
type (
WaitWithContextFunc func(ctx context.Context) <-chan struct{}
ConditionWithContextFunc func(context.Context) (done bool, err error)
)

func PollImmediateWithContext(ctx context.Context, interval, timeout time.Duration, condition ConditionWithContextFunc) error {
return poll(ctx, true, poller(interval, timeout), condition)
Expand Down
5 changes: 0 additions & 5 deletions api/common/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ package utils

// IsStringInSlice checks if a string is an element of a string slice
func IsStringInSlice(str string, list []string) bool {

for _, b := range list {
if b == str {
return true
Expand All @@ -29,7 +28,6 @@ func IsStringInSlice(str string, list []string) bool {

// IsStringInSlices checks if a string is an element of a any of the string slices
func IsStringInSlices(str string, list ...[]string) bool {

for _, strs := range list {
if IsStringInSlice(str, strs) {
return true
Expand All @@ -41,7 +39,6 @@ func IsStringInSlices(str string, list ...[]string) bool {

// RemoveStringFromSlice returns a slice that is a copy of the input "list" slice with the input "str" string removed
func RemoveStringFromSlice(str string, list []string) []string {

result := make([]string, 0)

for _, v := range list {
Expand All @@ -55,11 +52,9 @@ func RemoveStringFromSlice(str string, list []string) []string {

// RemoveStringsFromSlice generates a slice that is a copy of the input "list" slice with elements from the input "strs" slice removed
func RemoveStringsFromSlice(filters []string, list []string) []string {

result := make([]string, 0)

for _, str := range list {

if !IsStringInSlice(str, filters) {
result = append(result, str)
}
Expand Down
15 changes: 6 additions & 9 deletions api/common/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,17 @@ func TestMain(m *testing.M) {
}

func TestIsStringInSlice(t *testing.T) {

var list = []string{"hello", "world", "jason"}
list := []string{"hello", "world", "jason"}

assert.True(t, IsStringInSlice("world", list))
assert.False(t, IsStringInSlice("mary", list))
assert.False(t, IsStringInSlice("harry", nil))
}

func TestRemoveStringFromSlice(t *testing.T) {
list := []string{"hello", "world", "jason"}

var list = []string{"hello", "world", "jason"}

var result = RemoveStringFromSlice("hello", list)
result := RemoveStringFromSlice("hello", list)

assert.Equal(t, 3, len(list))
assert.Equal(t, 2, len(result))
Expand All @@ -50,12 +48,11 @@ func TestRemoveStringFromSlice(t *testing.T) {
}

func TestRemoveStringsFromSlice(t *testing.T) {
list := []string{"hello", "world", "jason"}

var list = []string{"hello", "world", "jason"}

var filterList = []string{"hello", "there", "chap", "world"}
filterList := []string{"hello", "there", "chap", "world"}

var result = RemoveStringsFromSlice(filterList, list)
result := RemoveStringsFromSlice(filterList, list)

assert.Equal(t, 1, len(result))
}
Loading
Loading