Added test cases for Delete (#8)

* Completed List cmd and added API calls

* Minor comments and add delete code to pass linting

* Typo in descriptions

* Minor comments

* Validations

* Validations-1

* improved branch flag validation

* removed build

* working after refactory with bad names

* Command working, test not working

* Corrected creation of service

* Finalized structure using service

* Deleted tests

* cleanup

* cleanup

* cleanup

* removed space with tab

* aligned types in model.go

* Update model.go

* resolved comments

* Refactor

* removed long descriptions

* Working incomplete tests

* Completed tests

* cleanup

* checks

* PR comments

* PR comments

* minor comment issue

* minor comment issue

* Added test cases for Delete

* updated tests to work with workflow

* Added missing error condition

* Updated tests to support new option service

* Improved eror handling for list

* Fixed test case

* Improved error handling

* Error handling and test cases for delete API calls

* Added test case for user confirmation delete.

* Removed unused import from test

* Fixed test case for error scenario

* Upgraded go-gh

* reusing rest client error

* Fix for failing windows test cases

* help cmd removed when cache isnt present on delete

* Pretty print ratio and space between cols modified

* Error handling wrapping

* Reverted back error message after silencing help

Co-authored-by: t-dedah <t-dedah@github.com>
Co-authored-by: Deepak Dahiya <59823596+t-dedah@users.noreply.github.com>
This commit is contained in:
Sankalp Kotewar
2022-07-14 02:33:36 +05:30
committed by GitHub
parent db34270ecb
commit 790f19d8a6
5 changed files with 237 additions and 49 deletions

View File

@@ -1,6 +1,7 @@
package cmd
import (
"errors"
"fmt"
"net/url"
"strings"
@@ -9,9 +10,12 @@ import (
"github.com/actions/gh-actions-cache/internal"
"github.com/actions/gh-actions-cache/service"
"github.com/actions/gh-actions-cache/types"
"github.com/cli/go-gh/pkg/api"
"github.com/spf13/cobra"
)
var choice string = ""
func NewCmdDelete() *cobra.Command {
COMMAND = "delete"
f := types.DeleteOptions{}
@@ -31,11 +35,12 @@ func NewCmdDelete() *cobra.Command {
return err
}
// This will silence the usage (help) message as they are not needed for errors beyond this point
cmd.SilenceUsage = true
artifactCache, err := service.NewArtifactCache(repo, COMMAND, VERSION)
if err != nil {
fmt.Printf("error connecting to %s\n", repo.Host())
fmt.Println("check your internet connection or https://githubstatus.com")
return nil
return types.HandledError{Message: err.Error(), InnerError: err}
}
queryParams := url.Values{}
@@ -44,7 +49,14 @@ func NewCmdDelete() *cobra.Command {
if !f.Confirm {
matchedCaches, err := getCacheListWithExactMatch(f, artifactCache)
if err != nil {
return err
var httpError api.HTTPError
if errors.As(err, &httpError) && httpError.StatusCode == 404 {
return types.HandledError{Message: "The given repo does not exist.", InnerError: err}
} else if errors.As(err, &httpError) && httpError.StatusCode >= 400 && httpError.StatusCode < 500 {
return types.HandledError{Message: httpError.Message, InnerError: err}
} else {
return types.HandledError{Message: "We could not process your request due to internal error.", InnerError: err}
}
}
matchedCachesLen := len(matchedCaches)
if matchedCachesLen == 0 {
@@ -52,22 +64,31 @@ func NewCmdDelete() *cobra.Command {
}
fmt.Printf("You're going to delete %s", internal.PrintSingularOrPlural(matchedCachesLen, "cache entry\n\n", "cache entries\n\n"))
internal.PrettyPrintTrimmedCacheList(matchedCaches)
choice := ""
prompt := &survey.Select{
Message: "Are you sure you want to delete the cache entries?",
Options: []string{"Delete", "Cancel"},
}
err = survey.AskOne(prompt, &choice)
if err != nil {
return fmt.Errorf("Error occured while taking input from user while trying to delete cache")
fmt.Println("Error occured while taking input from user while trying to delete cache")
return types.HandledError{Message: "Error occured while taking input from user while trying to delete cache.", InnerError: err}
}
f.Confirm = choice == "Delete"
fmt.Println()
}
if f.Confirm {
cachesDeleted, err := artifactCache.DeleteCaches(queryParams)
if err != nil {
return err
var httpError api.HTTPError
if errors.As(err, &httpError) && httpError.StatusCode == 404 {
return types.HandledError{Message: fmt.Sprintf("Cache with input key '%s' does not exist", f.Key), InnerError: err}
} else if errors.As(err, &httpError) && httpError.StatusCode >= 400 && httpError.StatusCode < 500 {
return types.HandledError{Message: httpError.Message, InnerError: err}
} else {
return types.HandledError{Message: "We could not process your request due to internal error.", InnerError: err}
}
}
if cachesDeleted > 0 {

171
cmd/delete_test.go Normal file
View File

@@ -0,0 +1,171 @@
package cmd
import (
"errors"
"fmt"
"reflect"
"testing"
"github.com/actions/gh-actions-cache/internal"
"github.com/actions/gh-actions-cache/types"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
func TestDeleteWithIncorrectArguments(t *testing.T) {
t.Cleanup(gock.Off)
cmd := NewCmdDelete()
cmd.SetArgs([]string{})
err := cmd.Execute()
assert.NotNil(t, err)
assert.Equal(t, err, fmt.Errorf("accepts 1 arg(s), received 0"))
assert.True(t, gock.IsDone(), internal.PrintPendingMocks(gock.Pending()))
}
func TestDeleteWithIncorrectRepo(t *testing.T) {
t.Cleanup(gock.Off)
cmd := NewCmdDelete()
cmd.SetArgs([]string{"--repo", "testOrg/testRepo/123/123", "cacheName"})
err := cmd.Execute()
assert.NotNil(t, err)
assert.Equal(t, err, fmt.Errorf("expected the \"[HOST/]OWNER/REPO\" format, got \"testOrg/testRepo/123/123\""))
assert.True(t, gock.IsDone(), internal.PrintPendingMocks(gock.Pending()))
}
func TestDeleteWithIncorrectRepoForDeleteCaches(t *testing.T) {
t.Cleanup(gock.Off)
gock.New("https://api.github.com").
Get("/repos/testOrg/testRepo/actions/caches").
MatchParam("key", "cacheName").
Reply(404).
JSON(`{
"message": "Not Found",
"documentation_url": "https://docs.github.com/rest/actions/cache#list-github-actions-caches-for-a-repository"
}`)
cmd := NewCmdDelete()
cmd.SetArgs([]string{"--repo", "testOrg/testRepo", "cacheName"})
err := cmd.Execute()
assert.NotNil(t, err)
assert.True(t, gock.IsDone(), internal.PrintPendingMocks(gock.Pending()))
var customError types.HandledError
errors.As(err, &customError)
assert.Equal(t, customError.Message, "The given repo does not exist.")
}
func TestDeleteSuccessWithConfirmFlagProvided(t *testing.T) {
t.Cleanup(gock.Off)
gock.New("https://api.github.com").
Delete("/repos/testOrg/testRepo/actions/caches").
MatchParam("key", "2022-06-29T13:33:49").
Reply(200).
JSON(`{
"total_count": 1,
"actions_caches": [
{
"id": 1293,
"ref": "refs/heads/main",
"key": "2022-06-29T13:33:49",
"version": "803758043e242677f6b8650742372d82ded436d99b2a8a09bc3b6ed77cd6aec2",
"last_accessed_at": "2022-06-29T13:33:52.280000000Z",
"created_at": "2022-06-29T13:33:52.280000000Z",
"size_in_bytes": 29747
}
]
}`)
cmd := NewCmdDelete()
cmd.SetArgs([]string{"--repo", "testOrg/testRepo", "2022-06-29T13:33:49", "--confirm"})
err := cmd.Execute()
assert.Nil(t, err)
assert.True(t, gock.IsDone(), internal.PrintPendingMocks(gock.Pending()))
}
func TestDeleteFailureWhileTakingUserInput(t *testing.T) {
t.Cleanup(gock.Off)
choice = "Delete"
gock.New("https://api.github.com").
Get("/repos/testOrg/testRepo/actions/caches").
MatchParam("key", "2022-06-29T13:33:49").
Reply(200).
JSON(`{
"total_count": 1,
"actions_caches": [
{
"id": 1293,
"ref": "refs/heads/main",
"key": "2022-06-29T13:33:49",
"version": "803758043e242677f6b8650742372d82ded436d99b2a8a09bc3b6ed77cd6aec2",
"last_accessed_at": "2022-06-29T13:33:52.280000000Z",
"created_at": "2022-06-29T13:33:52.280000000Z",
"size_in_bytes": 29747
}
]
}`)
cmd := NewCmdDelete()
cmd.SetArgs([]string{"--repo", "testOrg/testRepo", "2022-06-29T13:33:49"})
err := cmd.Execute()
assert.NotNil(t, err)
assert.True(t, gock.IsDone(), internal.PrintPendingMocks(gock.Pending()))
}
func TestDeleteWithUnauthorizedRequestForDeleteCaches(t *testing.T) {
t.Cleanup(gock.Off)
gock.New("https://api.github.com").
Delete("/repos/testOrg/testRepo/actions/caches").
Reply(401).
JSON(`{
"message": "Must have admin rights to Repository.",
"documentation_url": "https://docs.github.com/rest/actions/cache#delete-a-github-actions-cache-for-a-repository-using-a-cache-id"
}`)
cmd := NewCmdDelete()
cmd.SetArgs([]string{"--repo", "testOrg/testRepo", "cacheKey", "--confirm"})
err := cmd.Execute()
assert.NotNil(t, err)
assert.Equal(t, reflect.TypeOf(err), reflect.TypeOf(types.HandledError{}))
var customError types.HandledError
errors.As(err, &customError)
assert.Equal(t, customError.Message, "Must have admin rights to Repository.")
assert.True(t, gock.IsDone(), internal.PrintPendingMocks(gock.Pending()))
}
func TestDeleteWithInternalServerErrorForDeleteCaches(t *testing.T) {
t.Cleanup(gock.Off)
gock.New("https://api.github.com").
Delete("/repos/testOrg/testRepo/actions/caches").
Reply(500).
JSON(`{
"message": "Internal Server Error",
"documentation_url": "https://docs.github.com/rest/reference/actions#get-github-actions-cache-Delete-for-a-repository"
}`)
cmd := NewCmdDelete()
cmd.SetArgs([]string{"--repo", "testOrg/testRepo", "cacheKey", "--confirm"})
err := cmd.Execute()
assert.NotNil(t, err)
assert.Equal(t, reflect.TypeOf(err), reflect.TypeOf(types.HandledError{}))
var customError types.HandledError
errors.As(err, &customError)
assert.Equal(t, customError.Message, "We could not process your request due to internal error.")
assert.True(t, gock.IsDone(), internal.PrintPendingMocks(gock.Pending()))
}