|
6 | 6 | "os" |
7 | 7 | "path" |
8 | 8 | "testing" |
| 9 | + "time" |
9 | 10 |
|
10 | 11 | "github.com/linuxsuren/http-downloader/pkg/installer" |
11 | 12 | "github.com/spf13/cobra" |
@@ -36,6 +37,45 @@ func Test_newFetchCmd(t *testing.T) { |
36 | 37 | } |
37 | 38 | } |
38 | 39 |
|
| 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 | + |
39 | 79 | func TestFetchPreRunE(t *testing.T) { |
40 | 80 | tests := []struct { |
41 | 81 | name string |
@@ -82,13 +122,36 @@ func TestFetchRunE(t *testing.T) { |
82 | 122 | name string |
83 | 123 | opt *fetchOption |
84 | 124 | 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, |
89 | 132 | }, |
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 | + |
92 | 155 | for _, tt := range tests { |
93 | 156 | t.Run(tt.name, func(t *testing.T) { |
94 | 157 | c := &cobra.Command{} |
|
0 commit comments