Skip to content

Commit de7232b

Browse files
Add unit test for fetch.go (#484)
Co-authored-by: yazied_uddien <[email protected]>
1 parent 016a1cb commit de7232b

File tree

1 file changed

+69
-6
lines changed

1 file changed

+69
-6
lines changed

cmd/fetch_test.go

Lines changed: 69 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"os"
77
"path"
88
"testing"
9+
"time"
910

1011
"github.com/linuxsuren/http-downloader/pkg/installer"
1112
"github.com/spf13/cobra"
@@ -36,6 +37,45 @@ func Test_newFetchCmd(t *testing.T) {
3637
}
3738
}
3839

40+
func TestSetTimeoutWithContext(t *testing.T) {
41+
tests := []struct {
42+
name string
43+
context context.Context
44+
timeout time.Duration
45+
expected bool
46+
}{
47+
{
48+
name: "context with timeout",
49+
context: context.Background(),
50+
timeout: time.Second * 10,
51+
expected: true,
52+
},
53+
{
54+
name: "context without timeout",
55+
context: nil,
56+
timeout: time.Second * 10,
57+
expected: false,
58+
},
59+
}
60+
61+
for _, tt := range tests {
62+
t.Run(tt.name, func(t *testing.T) {
63+
cmd := &cobra.Command{}
64+
cmd.SetContext(tt.context)
65+
opt := &fetchOption{
66+
timeout: tt.timeout,
67+
fetcher: &installer.FakeFetcher{},
68+
}
69+
opt.setTimeout(cmd)
70+
if tt.expected {
71+
assert.NotNil(t, opt.cancel)
72+
} else {
73+
assert.Nil(t, opt.cancel)
74+
}
75+
})
76+
}
77+
}
78+
3979
func TestFetchPreRunE(t *testing.T) {
4080
tests := []struct {
4181
name string
@@ -82,13 +122,36 @@ func TestFetchRunE(t *testing.T) {
82122
name string
83123
opt *fetchOption
84124
hasErr bool
85-
}{{
86-
name: "normal",
87-
opt: &fetchOption{
88-
fetcher: &installer.FakeFetcher{},
125+
}{
126+
{
127+
name: "normal",
128+
opt: &fetchOption{
129+
fetcher: &installer.FakeFetcher{},
130+
},
131+
hasErr: false,
89132
},
90-
hasErr: false,
91-
}}
133+
{
134+
name: "fetch with retry",
135+
opt: &fetchOption{
136+
fetcher: &installer.FakeFetcher{
137+
FetchLatestRepoErr: errors.New("context deadline exceeded"),
138+
},
139+
retry: 3,
140+
},
141+
hasErr: true,
142+
},
143+
{
144+
name: "fetch with non-retryable error",
145+
opt: &fetchOption{
146+
fetcher: &installer.FakeFetcher{
147+
FetchLatestRepoErr: errors.New("some other error"),
148+
},
149+
retry: 3,
150+
},
151+
hasErr: true,
152+
},
153+
}
154+
92155
for _, tt := range tests {
93156
t.Run(tt.name, func(t *testing.T) {
94157
c := &cobra.Command{}

0 commit comments

Comments
 (0)