Skip to content

Commit

Permalink
Add unit test for fetch.go (#484)
Browse files Browse the repository at this point in the history
Co-authored-by: yazied_uddien <yazied_uddien@linkaja.id>
  • Loading branch information
yaziedda and yaziedda-la authored Oct 8, 2024
1 parent 016a1cb commit de7232b
Showing 1 changed file with 69 additions and 6 deletions.
75 changes: 69 additions & 6 deletions cmd/fetch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"path"
"testing"
"time"

"github.com/linuxsuren/http-downloader/pkg/installer"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -36,6 +37,45 @@ func Test_newFetchCmd(t *testing.T) {
}
}

func TestSetTimeoutWithContext(t *testing.T) {
tests := []struct {
name string
context context.Context
timeout time.Duration
expected bool
}{
{
name: "context with timeout",
context: context.Background(),
timeout: time.Second * 10,
expected: true,
},
{
name: "context without timeout",
context: nil,
timeout: time.Second * 10,
expected: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := &cobra.Command{}
cmd.SetContext(tt.context)
opt := &fetchOption{
timeout: tt.timeout,
fetcher: &installer.FakeFetcher{},
}
opt.setTimeout(cmd)
if tt.expected {
assert.NotNil(t, opt.cancel)
} else {
assert.Nil(t, opt.cancel)
}
})
}
}

func TestFetchPreRunE(t *testing.T) {
tests := []struct {
name string
Expand Down Expand Up @@ -82,13 +122,36 @@ func TestFetchRunE(t *testing.T) {
name string
opt *fetchOption
hasErr bool
}{{
name: "normal",
opt: &fetchOption{
fetcher: &installer.FakeFetcher{},
}{
{
name: "normal",
opt: &fetchOption{
fetcher: &installer.FakeFetcher{},
},
hasErr: false,
},
hasErr: false,
}}
{
name: "fetch with retry",
opt: &fetchOption{
fetcher: &installer.FakeFetcher{
FetchLatestRepoErr: errors.New("context deadline exceeded"),
},
retry: 3,
},
hasErr: true,
},
{
name: "fetch with non-retryable error",
opt: &fetchOption{
fetcher: &installer.FakeFetcher{
FetchLatestRepoErr: errors.New("some other error"),
},
retry: 3,
},
hasErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &cobra.Command{}
Expand Down

0 comments on commit de7232b

Please sign in to comment.