-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathmain_test.go
More file actions
344 lines (300 loc) · 11.5 KB
/
main_test.go
File metadata and controls
344 lines (300 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// e2e test for nsx-operator, in nsx_operator directory, run the command below:
// e2e=true go test -v github.com/vmware-tanzu/nsx-operator/test/e2e -remote.sshconfig /root/.ssh/config -remote.kubeconfig /root/.kube/config
// -operator-cfg-path /etc/nsx-ujo/ncp.ini -test.timeout 15m
// Note: set a reasonable timeout when running e2e tests, otherwise the test will be terminated by the framework.
package e2e
import (
"flag"
"fmt"
"os"
"os/signal"
"sort"
"strings"
"sync"
"syscall"
"testing"
"time"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"github.com/vmware-tanzu/nsx-operator/pkg/logger"
)
// TestResult holds information about a single test result
type TestResult struct {
Name string
Passed bool
Skipped bool
Duration time.Duration
StartTime time.Time
}
// TestResultTracker tracks test results for summary reporting
type TestResultTracker struct {
mu sync.Mutex
results map[string]*TestResult
startTime time.Time
}
var testResultTracker = &TestResultTracker{
results: make(map[string]*TestResult),
}
// StartTest marks a test as started
func (tr *TestResultTracker) StartTest(name string) {
tr.mu.Lock()
defer tr.mu.Unlock()
tr.results[name] = &TestResult{
Name: name,
StartTime: time.Now(),
}
}
// EndTest marks a test as completed with its result
func (tr *TestResultTracker) EndTest(name string, passed, skipped bool) {
tr.mu.Lock()
defer tr.mu.Unlock()
if result, exists := tr.results[name]; exists {
result.Passed = passed
result.Skipped = skipped
result.Duration = time.Since(result.StartTime)
}
}
// TrackTest registers a test and automatically records its result when it completes.
// Call this at the beginning of each top-level test function:
//
// func TestSomething(t *testing.T) {
// TrackTest(t)
// // ... test logic ...
// }
func TrackTest(t *testing.T) {
testResultTracker.StartTest(t.Name())
t.Cleanup(func() {
testResultTracker.EndTest(t.Name(), !t.Failed(), t.Skipped())
})
}
// RunSubtest runs a subtest and automatically tracks its result.
// Use this instead of t.Run() to include subtests in the test summary tree.
//
// RunSubtest(t, "subtestName", func(t *testing.T) {
// // ... subtest logic ...
// })
func RunSubtest(t *testing.T, name string, f func(t *testing.T)) bool {
return t.Run(name, func(t *testing.T) {
testResultTracker.StartTest(t.Name())
t.Cleanup(func() {
testResultTracker.EndTest(t.Name(), !t.Failed(), t.Skipped())
})
f(t)
})
}
// testTreeNode represents a node in the test hierarchy tree
type testTreeNode struct {
name string
result *TestResult // nil for intermediate nodes
children map[string]*testTreeNode
}
// buildTestTree builds a tree structure from test names (e.g., "TestA/SubB/SubC")
func buildTestTree(results map[string]*TestResult) *testTreeNode {
root := &testTreeNode{name: "root", children: make(map[string]*testTreeNode)}
for name, result := range results {
parts := strings.Split(name, "/")
current := root
for i, part := range parts {
if current.children[part] == nil {
current.children[part] = &testTreeNode{
name: part,
children: make(map[string]*testTreeNode),
}
}
current = current.children[part]
// Set result on the leaf node
if i == len(parts)-1 {
current.result = result
}
}
}
return root
}
// getStatusIcon returns the appropriate icon for test status
func getStatusIcon(result *TestResult) string {
if result == nil {
return "📁"
}
if result.Skipped {
return "⏭️ "
}
if result.Passed {
return "✅"
}
return "❌"
}
// printTreeNode recursively prints a tree node with proper indentation
func printTreeNode(node *testTreeNode, prefix string, isLast bool, results map[string]*TestResult) {
// Sort children for consistent output
var childNames []string
for name := range node.children {
childNames = append(childNames, name)
}
sort.Strings(childNames)
for i, childName := range childNames {
child := node.children[childName]
isLastChild := i == len(childNames)-1
// Determine the connector
connector := "├── "
if isLastChild {
connector = "└── "
}
// Get status icon and duration
icon := getStatusIcon(child.result)
durationStr := ""
if child.result != nil {
durationStr = fmt.Sprintf(" (%s)", child.result.Duration.Round(time.Millisecond))
}
fmt.Printf("%s%s%s %s%s\n", prefix, connector, icon, child.name, durationStr)
// Recursively print children
newPrefix := prefix
if isLastChild {
newPrefix += " "
} else {
newPrefix += "│ "
}
printTreeNode(child, newPrefix, isLastChild, results)
}
}
// PrintSummary prints a summary of all test results in tree format
func (tr *TestResultTracker) PrintSummary() {
tr.mu.Lock()
defer tr.mu.Unlock()
if len(tr.results) == 0 {
return
}
var passed, failed, skipped int
// Calculate actual wall-clock duration from start to end of all tests
totalDuration := time.Since(tr.startTime)
for _, result := range tr.results {
if result.Skipped {
skipped++
} else if result.Passed {
passed++
} else {
failed++
}
}
// Print summary header
fmt.Println()
fmt.Println(strings.Repeat("=", 80))
fmt.Println(" E2E TEST SUMMARY")
fmt.Println(strings.Repeat("=", 80))
fmt.Printf("Total: %d | Passed: %d | Failed: %d | Skipped: %d\n",
len(tr.results), passed, failed, skipped)
fmt.Printf("Total Duration: %s\n", totalDuration.Round(time.Second))
fmt.Println(strings.Repeat("-", 80))
// Build and print tree structure
fmt.Println("\n📊 TEST RESULTS:")
tree := buildTestTree(tr.results)
printTreeNode(tree, "", true, tr.results)
// Print failed tests summary if any
if failed > 0 {
fmt.Println("\n" + strings.Repeat("-", 80))
fmt.Println("❌ FAILED TESTS SUMMARY:")
var failedNames []string
for name, result := range tr.results {
if !result.Passed && !result.Skipped {
failedNames = append(failedNames, name)
}
}
sort.Strings(failedNames)
for _, name := range failedNames {
fmt.Printf(" • %s\n", name)
}
}
fmt.Println(strings.Repeat("=", 80))
if failed > 0 {
fmt.Printf("RESULT: ❌ FAILED (%d test(s) failed)\n", failed)
} else {
fmt.Println("RESULT: ✅ ALL TESTS PASSED")
}
fmt.Println(strings.Repeat("=", 80))
fmt.Println()
}
// testMain is meant to be called by TestMain and enables the use of defer statements.
func testMain(m *testing.M) int {
flag.StringVar(&testOptions.providerName, "provider", "remote", "K8s test cluster provider")
flag.StringVar(&testOptions.providerConfigPath, "provider-cfg-path", "", "Optional config file for provider")
flag.StringVar(&testOptions.logsExportDir, "logs-export-dir", "", "Export directory for test logs")
flag.StringVar(&testOptions.operatorConfigPath, "operator-cfg-path", "/etc/nsx-ujo/ncp.ini", "config file for operator")
flag.BoolVar(&testOptions.logsExportOnSuccess, "logs-export-on-success", false, "Export logs even when a test is successful")
flag.StringVar(&testOptions.vcUser, "vc-user", "", "The username used to request vCenter API session")
flag.StringVar(&testOptions.vcPassword, "vc-password", "", "The password used by the user when requesting vCenter API session")
flag.BoolVar(&testOptions.debugLog, "debug", false, "")
flag.IntVar(&testOptions.logLevel, "log-level", 0, "")
flag.BoolVar(&testOptions.logColor, "log-color", false, "Enable ANSI color in log output.")
flag.Parse()
log = logger.ZapCustomLogger(testOptions.debugLog, testOptions.logLevel, testOptions.logColor)
logger.Log = log
// Set the controller-runtime logger to prevent the warning about log.SetLogger(...) never being called
logf.SetLogger(log.Logger)
if err := initProvider(); err != nil {
log.Error(err, "Error when initializing provider")
panic(err)
}
log.Info("Creating clientSets")
if err := NewTestData(testOptions.operatorConfigPath, testOptions.vcUser, testOptions.vcPassword); err != nil {
log.Error(err, "Error when creating client")
return 1
}
log.Info("Collecting information about K8s cluster")
if err := collectClusterInfo(); err != nil {
log.Error(err, "Error when collecting information about K8s cluster")
panic(err)
}
if clusterInfo.podV4NetworkCIDR != "" {
log.Info("Pod IPv4: ", "network", clusterInfo.podV4NetworkCIDR)
}
if clusterInfo.podV6NetworkCIDR != "" {
log.Info("Pod IPv6: ", "network", clusterInfo.podV6NetworkCIDR)
}
// Batch create all VC namespaces once
if err := InitAllNamespaces(); err != nil {
log.Error(err, "failed to init all e2e namespaces")
}
// Handle Ctrl+C to trigger cleanup
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigChan
log.Info("Received signal, triggering cleanup", "signal", sig)
CleanupAllNamespaces()
os.Exit(1)
}()
// Set up a timeout for the entire e2e test suite (30 minutes)
const e2eTimeout = 30 * time.Minute
timeoutChan := time.After(e2eTimeout)
go func() {
<-timeoutChan
log.Info("⚠️ WARNING: E2E test suite exceeded timeout, forcing cleanup", "timeout", e2eTimeout)
testResultTracker.PrintSummary()
CleanupAllNamespaces()
os.Exit(1)
}()
// Print ASCII art banner
fmt.Println()
fmt.Println("╔════════════════════════════════════════════════════════════════════════════════╗")
fmt.Println("║ ║")
fmt.Println("║ ███╗ ██╗███████╗██╗ ██╗ ██████╗ ██████╗ ███████╗██████╗ █████╗ ║")
fmt.Println("║ ████╗ ██║██╔════╝╚██╗██╔╝ ██╔═══██╗██╔══██╗██╔════╝██╔══██╗██╔══██╗ ║")
fmt.Println("║ ██╔██╗ ██║███████╗ ╚███╔╝ ██║ ██║██████╔╝█████╗ ██████╔╝███████║ ║")
fmt.Println("║ ██║╚██╗██║╚════██║ ██╔██╗ ██║ ██║██╔═══╝ ██╔══╝ ██╔══██╗██╔══██║ ║")
fmt.Println("║ ██║ ╚████║███████║██╔╝ ██╗ ╚██████╔╝██║ ███████╗██║ ██║██║ ██║ ║")
fmt.Println("║ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ║")
fmt.Println("║ ║")
fmt.Println("║ 🧪 End-to-End Test Suite 🧪 ║")
fmt.Println("║ ║")
fmt.Println("╚════════════════════════════════════════════════════════════════════════════════╝")
fmt.Println()
testResultTracker.startTime = time.Now()
ret := m.Run()
// Print test summary at the end
testResultTracker.PrintSummary()
CleanupAllNamespaces()
return ret
}
func TestMain(m *testing.M) {
if os.Getenv("e2e") == "true" {
os.Exit(testMain(m))
}
}