Skip to content

Commit

Permalink
feat: Add storage delete command (#831)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexplischke authored Sep 7, 2023
1 parent 2db4c2b commit c0ed293
Show file tree
Hide file tree
Showing 6 changed files with 187 additions and 0 deletions.
1 change: 1 addition & 0 deletions internal/cmd/storage/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func Command(preRun func(cmd *cobra.Command, args []string)) *cobra.Command {
ListCommand(),
UploadCommand(),
DownloadCommand(),
DeleteCommand(),
)

return cmd
Expand Down
50 changes: 50 additions & 0 deletions internal/cmd/storage/delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package storage

import (
"errors"
"fmt"

cmds "github.com/saucelabs/saucectl/internal/cmd"
"github.com/saucelabs/saucectl/internal/segment"
"github.com/saucelabs/saucectl/internal/usage"
"github.com/spf13/cobra"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)

func DeleteCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "delete <fileID>",
Short: "Delete a file from Sauce Storage.",
SilenceUsage: true,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 || args[0] == "" {
return errors.New("no ID specified")
}

return nil
},
PreRun: func(cmd *cobra.Command, args []string) {
tracker := segment.DefaultTracker

go func() {
tracker.Collect(
cases.Title(language.English).String(cmds.FullName(cmd)),
usage.Properties{}.SetFlags(cmd.Flags()),
)
_ = tracker.Close()
}()
},
RunE: func(cmd *cobra.Command, args []string) error {
if err := appsClient.Delete(args[0]); err != nil {
return fmt.Errorf("failed to delete file: %v", err)
}

println("File deleted successfully!")

return nil
},
}

return cmd
}
31 changes: 31 additions & 0 deletions internal/http/appstore.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,37 @@ func (s *AppStore) List(opts storage.ListOptions) (storage.List, error) {
}
}

func (s *AppStore) Delete(id string) error {
if id == "" {
return fmt.Errorf("no id specified")
}

req, err := retryablehttp.NewRequest(http.MethodDelete, fmt.Sprintf("%s/v1/storage/files/%s", s.URL, id), nil)
if err != nil {
return err
}

req.SetBasicAuth(s.Username, s.AccessKey)

resp, err := s.HTTPClient.Do(req)
if err != nil {
return err
}

switch resp.StatusCode {
case 200:
return nil
case 401, 403:
return storage.ErrAccessDenied
case 404:
return storage.ErrFileNotFound
case 429:
return storage.ErrTooManyRequest
default:
return s.newServerError(resp)
}
}

// newServerError inspects server error responses, trying to gather as much information as possible, especially if the body
// conforms to the errorResponse format, and returns a storage.ServerError.
func (s *AppStore) newServerError(resp *http.Response) *storage.ServerError {
Expand Down
100 changes: 100 additions & 0 deletions internal/http/appstore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ import (
"net/http"
"net/http/httptest"
"os"
"path"
"reflect"
"strings"
"testing"
"time"

"github.com/hashicorp/go-retryablehttp"
"github.com/saucelabs/saucectl/internal/storage"
"github.com/stretchr/testify/assert"
"github.com/xtgo/uuid"

"gotest.tools/v3/fs"
Expand Down Expand Up @@ -318,3 +321,100 @@ func TestAppStore_List(t *testing.T) {
})
}
}

func TestAppStore_Delete(t *testing.T) {
testUser := "test"
testPass := "test"

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}

if !strings.HasPrefix(r.URL.Path, "/v1/storage/files/") {
w.WriteHeader(http.StatusNotImplemented)
_, _ = w.Write([]byte("incorrect path"))
return
}
println(path.Base(r.URL.Path))
if path.Base(r.URL.Path) == "" {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte("missing file id"))
return
}

user, pass, _ := r.BasicAuth()
if user != testUser || pass != testPass {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(http.StatusText(http.StatusForbidden)))
return
}

w.WriteHeader(200)
// The real server's response body contains a JSON that describes the
// deleted item. We don't need that for this test.
}))
defer server.Close()

type fields struct {
HTTPClient *retryablehttp.Client
URL string
Username string
AccessKey string
}
type args struct {
id string
}
tests := []struct {
name string
fields fields
args args
wantErr assert.ErrorAssertionFunc
}{
{
name: "delete item successfully",
fields: fields{
HTTPClient: NewRetryableClient(10 * time.Second),
URL: server.URL,
Username: testUser,
AccessKey: testPass,
},
args: args{id: uuid.NewRandom().String()},
wantErr: assert.NoError,
},
{
name: "fail on wrong credentials",
fields: fields{
HTTPClient: NewRetryableClient(10 * time.Second),
URL: server.URL,
Username: testUser + "1",
AccessKey: testPass + "1",
},
args: args{id: uuid.NewRandom().String()},
wantErr: assert.Error,
},
{
name: "fail when no ID was specified",
fields: fields{
HTTPClient: NewRetryableClient(10 * time.Second),
URL: server.URL,
Username: testUser,
AccessKey: testPass,
},
args: args{id: ""},
wantErr: assert.Error,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &AppStore{
HTTPClient: tt.fields.HTTPClient,
URL: tt.fields.URL,
Username: tt.fields.Username,
AccessKey: tt.fields.AccessKey,
}
tt.wantErr(t, s.Delete(tt.args.id), fmt.Sprintf("Delete(%v)", tt.args.id))
})
}
}
4 changes: 4 additions & 0 deletions internal/saucecloud/retry/saucereportretrier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ func (f *StubProjectUploader) List(opts storage.ListOptions) (storage.List, erro
return storage.List{}, nil
}

func (f *StubProjectUploader) Delete(id string) error {
return nil
}

type StubVDCJobReader struct {
SauceReport saucereport.SauceReport
}
Expand Down
1 change: 1 addition & 0 deletions internal/storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ type AppService interface {
// UploadStream uploads the contents of reader and stores them under the given filename.
UploadStream(filename, description string, reader io.Reader) (Item, error)
Download(id string) (io.ReadCloser, int64, error)
Delete(id string) error
DownloadURL(url string) (io.ReadCloser, int64, error)
List(opts ListOptions) (List, error)
}

0 comments on commit c0ed293

Please sign in to comment.