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

Add unit test for fetch.go #484

Merged
merged 1 commit into from
Oct 8, 2024
Merged
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
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
Loading