summaryrefslogtreecommitdiff
path: root/internal/profiling/profiler_test.go
blob: 937661186e548081bfcff47f0b19df3c0b1000cd (plain)
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
package profiling

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

func TestProfiler(t *testing.T) {
	// Create temporary profile directory
	tmpDir := t.TempDir()

	t.Run("DisabledProfiler", func(t *testing.T) {
		cfg := Config{
			CPUProfile:  false,
			MemProfile:  false,
			ProfileDir:  tmpDir,
			CommandName: "test",
		}

		p := NewProfiler(cfg)
		if p.enabled {
			t.Error("Profiler should be disabled when no profiling is requested")
		}

		// Should not panic
		p.Stop()
		p.Snapshot("test")
		p.LogMetrics("test")
	})

	t.Run("CPUProfileOnly", func(t *testing.T) {
		cfg := Config{
			CPUProfile:  true,
			MemProfile:  false,
			ProfileDir:  tmpDir,
			CommandName: "testcpu",
		}

		p := NewProfiler(cfg)
		if !p.enabled {
			t.Error("Profiler should be enabled")
		}

		// Do some work to generate CPU samples
		doWork(100)

		p.Stop()

		// Check if CPU profile was created
		profiles, err := filepath.Glob(filepath.Join(tmpDir, "testcpu_cpu_*.prof"))
		if err != nil {
			t.Fatalf("Failed to list profiles: %v", err)
		}
		if len(profiles) == 0 {
			t.Error("No CPU profile generated")
		}

		// Verify profile exists and has content
		for _, profile := range profiles {
			info, err := os.Stat(profile)
			if err != nil {
				t.Errorf("Failed to stat profile %s: %v", profile, err)
			}
			if info.Size() == 0 {
				t.Errorf("Profile %s is empty", profile)
			}
		}
	})

	t.Run("MemProfileOnly", func(t *testing.T) {
		cfg := Config{
			CPUProfile:  false,
			MemProfile:  true,
			ProfileDir:  tmpDir,
			CommandName: "testmem",
		}

		p := NewProfiler(cfg)
		if !p.enabled {
			t.Error("Profiler should be enabled")
		}

		// Allocate some memory
		allocateMemory()

		p.Stop()

		// Check if memory profiles were created
		memProfiles, err := filepath.Glob(filepath.Join(tmpDir, "testmem_mem_*.prof"))
		if err != nil {
			t.Fatalf("Failed to list memory profiles: %v", err)
		}
		if len(memProfiles) == 0 {
			t.Error("No memory profile generated")
		}

		allocProfiles, err := filepath.Glob(filepath.Join(tmpDir, "testmem_alloc_*.prof"))
		if err != nil {
			t.Fatalf("Failed to list allocation profiles: %v", err)
		}
		if len(allocProfiles) == 0 {
			t.Error("No allocation profile generated")
		}
	})

	t.Run("BothProfiles", func(t *testing.T) {
		cfg := Config{
			CPUProfile:  true,
			MemProfile:  true,
			ProfileDir:  tmpDir,
			CommandName: "testboth",
		}

		p := NewProfiler(cfg)
		if !p.enabled {
			t.Error("Profiler should be enabled")
		}

		// Do work and allocate memory
		doWork(100)
		allocateMemory()

		p.Stop()

		// Check both profile types
		cpuProfiles, _ := filepath.Glob(filepath.Join(tmpDir, "testboth_cpu_*.prof"))
		memProfiles, _ := filepath.Glob(filepath.Join(tmpDir, "testboth_mem_*.prof"))
		allocProfiles, _ := filepath.Glob(filepath.Join(tmpDir, "testboth_alloc_*.prof"))

		if len(cpuProfiles) == 0 {
			t.Error("No CPU profile generated")
		}
		if len(memProfiles) == 0 {
			t.Error("No memory profile generated")
		}
		if len(allocProfiles) == 0 {
			t.Error("No allocation profile generated")
		}
	})

	t.Run("Snapshot", func(t *testing.T) {
		cfg := Config{
			CPUProfile:  false,
			MemProfile:  true,
			ProfileDir:  tmpDir,
			CommandName: "testsnap",
		}

		p := NewProfiler(cfg)
		
		// Take snapshots
		p.Snapshot("before")
		allocateMemory()
		p.Snapshot("after")

		p.Stop()

		// Check snapshots
		snapshots, err := filepath.Glob(filepath.Join(tmpDir, "testsnap_snapshot_*.prof"))
		if err != nil {
			t.Fatalf("Failed to list snapshots: %v", err)
		}
		
		foundBefore := false
		foundAfter := false
		for _, snapshot := range snapshots {
			if strings.Contains(snapshot, "_before_") {
				foundBefore = true
			}
			if strings.Contains(snapshot, "_after_") {
				foundAfter = true
			}
		}

		if !foundBefore {
			t.Error("Before snapshot not found")
		}
		if !foundAfter {
			t.Error("After snapshot not found")
		}
	})
}

func TestGetMetrics(t *testing.T) {
	metrics := GetMetrics()

	// Basic sanity checks
	if metrics.NumCPU <= 0 {
		t.Error("NumCPU should be positive")
	}
	if metrics.NumGoroutine <= 0 {
		t.Error("NumGoroutine should be positive")
	}
	if metrics.Alloc == 0 {
		t.Error("Alloc should not be zero")
	}
}

func TestFlags(t *testing.T) {
	f := Flags{}
	
	// Test default state
	if f.Enabled() {
		t.Error("Flags should not be enabled by default")
	}

	// Test individual flags
	f.CPUProfile = true
	if !f.Enabled() {
		t.Error("Should be enabled when CPUProfile is true")
	}

	f.CPUProfile = false
	f.MemProfile = true
	if !f.Enabled() {
		t.Error("Should be enabled when MemProfile is true")
	}

	f.MemProfile = false
	f.Profile = true
	if !f.Enabled() {
		t.Error("Should be enabled when Profile is true")
	}

	// Test ToConfig
	cfg := f.ToConfig("testcmd")
	if cfg.CommandName != "testcmd" {
		t.Error("CommandName not set correctly")
	}
	if !cfg.CPUProfile || !cfg.MemProfile {
		t.Error("Profile flag should enable both CPU and memory profiling")
	}
}

// Helper functions for testing

func doWork(iterations int) {
	// CPU-intensive work
	result := 0
	for i := 0; i < iterations*1000; i++ {
		for j := 0; j < 100; j++ {
			result += i * j
		}
	}
	_ = result
}

func allocateMemory() [][]byte {
	// Allocate some memory
	const numAllocs = 100
	const allocSize = 1024 * 1024 // 1MB

	allocations := make([][]byte, numAllocs)
	for i := 0; i < numAllocs; i++ {
		allocations[i] = make([]byte, allocSize)
		// Touch the memory to ensure it's allocated
		for j := 0; j < allocSize; j += 4096 {
			allocations[i][j] = byte(i)
		}
	}

	// Sleep briefly to allow profiler to capture state
	time.Sleep(10 * time.Millisecond)
	
	return allocations
}