|
1 | 1 | package jobs |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "bytes" |
4 | 5 | "context" |
| 6 | + "fmt" |
| 7 | + "log" |
5 | 8 | "path/filepath" |
6 | 9 | "strings" |
7 | 10 | "testing" |
8 | 11 | "time" |
9 | 12 |
|
| 13 | + "github.com/nginxinc/nginx-k8s-supportpkg/pkg/data_collector" |
10 | 14 | "github.com/nginxinc/nginx-k8s-supportpkg/pkg/mock" |
| 15 | + "github.com/stretchr/testify/assert" |
| 16 | + "go.uber.org/mock/gomock" |
| 17 | + "k8s.io/apimachinery/pkg/runtime" |
| 18 | + "k8s.io/client-go/kubernetes/fake" |
| 19 | + k8stesting "k8s.io/client-go/testing" // Add this line |
11 | 20 | ) |
12 | 21 |
|
13 | 22 | func TestCommonJobList_SelectedJobsProduceFiles(t *testing.T) { |
@@ -81,3 +90,55 @@ func TestCommonJobList_PodListJSONKeyPresence(t *testing.T) { |
81 | 90 | } |
82 | 91 | } |
83 | 92 | } |
| 93 | + |
| 94 | +func TestCommonJobList_PodListError(t *testing.T) { |
| 95 | + ctrl := gomock.NewController(t) |
| 96 | + defer ctrl.Finish() |
| 97 | + |
| 98 | + // Create mock clients |
| 99 | + mockClient := fake.NewSimpleClientset() |
| 100 | + |
| 101 | + // Add a reactor that returns an error for pod list operations |
| 102 | + mockClient.PrependReactor("list", "pods", func(action k8stesting.Action) (handled bool, ret runtime.Object, err error) { |
| 103 | + return true, nil, fmt.Errorf("mock API error: pods not available") |
| 104 | + }) |
| 105 | + |
| 106 | + // Setup data collector with error-prone client |
| 107 | + tmpDir := t.TempDir() |
| 108 | + var logOutput bytes.Buffer |
| 109 | + |
| 110 | + dc := &data_collector.DataCollector{ |
| 111 | + BaseDir: tmpDir, |
| 112 | + Namespaces: []string{"default", "test-namespace"}, |
| 113 | + Logger: log.New(&logOutput, "", 0), |
| 114 | + K8sCoreClientSet: mockClient, |
| 115 | + } |
| 116 | + |
| 117 | + // Execute the pod-list job |
| 118 | + var podJob []Job |
| 119 | + jobs := CommonJobList() |
| 120 | + for _, job := range jobs { |
| 121 | + if job.Name == "pod-list" || job.Name == "collect-pods-logs" { |
| 122 | + podJob = append(podJob, job) |
| 123 | + } |
| 124 | + } |
| 125 | + // podJob := jobs[0] // First job is pod-list |
| 126 | + |
| 127 | + ctx := context.Background() |
| 128 | + ch := make(chan JobResult, 1) |
| 129 | + for _, job := range podJob { |
| 130 | + job.Execute(dc, ctx, ch) |
| 131 | + |
| 132 | + result := <-ch |
| 133 | + |
| 134 | + // Assertions |
| 135 | + logContent := logOutput.String() |
| 136 | + assert.Contains(t, logContent, "Could not retrieve pod list for namespace default") |
| 137 | + assert.Contains(t, logContent, "Could not retrieve pod list for namespace test-namespace") |
| 138 | + assert.Contains(t, logContent, "mock API error: pods not available") |
| 139 | + |
| 140 | + // No files should be created since API calls failed |
| 141 | + assert.Empty(t, result.Files) |
| 142 | + assert.Nil(t, result.Error) // The job itself doesn't fail, just logs errors |
| 143 | + } |
| 144 | +} |
0 commit comments