Repository navigation
Expand file tree
/
Copy pathmain_test.go
More file actions
426 lines (361 loc) · 13 KB
/
Copy pathmain_test.go
File metadata and controls
426 lines (361 loc) · 13 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package main
import (
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
// TestPopulateVersionInfo tests the version population logic
func TestPopulateVersionInfo(t *testing.T) {
// Save original values
originalVersion := version
originalCommit := commit
defer func() {
version = originalVersion
commit = originalCommit
}()
t.Run("populates_version_info", func(t *testing.T) {
// Reset global variables
version = ""
commit = ""
// Call the function - it will use real git commands
populateVersionInfo()
// Check that values were populated
assert.NotEmpty(t, version, "Version should not be empty")
assert.NotEmpty(t, commit, "Commit should not be empty")
// Version should start with 'v'
assert.True(t, strings.HasPrefix(version, "v"), "Version should start with 'v'")
// Commit should be non-empty string (either a hash or "unknown")
assert.True(t, len(commit) > 0, "Commit should not be empty")
t.Logf("Generated version: %s", version)
t.Logf("Generated commit: %s", commit)
})
t.Run("handles_empty_initial_values", func(t *testing.T) {
// Test with explicitly empty values
version = ""
commit = ""
beforeVersion := version
beforeCommit := commit
populateVersionInfo()
// Should have changed from empty
assert.NotEqual(t, beforeVersion, version)
assert.NotEqual(t, beforeCommit, commit)
})
}
// TestInit tests the init function behavior
func TestInit(t *testing.T) {
// Save original values
originalVersion := version
originalCommit := commit
defer func() {
version = originalVersion
commit = originalCommit
}()
t.Run("init_logic_when_both_empty", func(t *testing.T) {
// Reset to empty (simulating no build-time injection)
version = ""
commit = ""
// Test the init logic: if version == "" && commit == "" { populateVersionInfo() }
if version == "" && commit == "" {
populateVersionInfo()
}
assert.NotEmpty(t, version)
assert.NotEmpty(t, commit)
})
t.Run("init_logic_when_version_set", func(t *testing.T) {
// Pre-set version but not commit (simulating partial build-time injection)
version = "v2.0.0"
commit = ""
originalVer := version
originalCom := commit
// The init logic: if version == "" && commit == "" { populateVersionInfo() }
// This should NOT call populateVersionInfo since version is not empty
shouldCallPopulate := version == "" && commit == ""
assert.False(t, shouldCallPopulate, "Should not call populateVersionInfo when version is set")
// Values should remain unchanged if we don't call populateVersionInfo
if !shouldCallPopulate {
assert.Equal(t, originalVer, version)
assert.Equal(t, originalCom, commit)
}
})
t.Run("init_logic_when_commit_set", func(t *testing.T) {
// Pre-set commit but not version
version = ""
commit = "build123"
originalVer := version
originalCom := commit
// The init logic: if version == "" && commit == "" { populateVersionInfo() }
// This should NOT call populateVersionInfo since commit is not empty
shouldCallPopulate := version == "" && commit == ""
assert.False(t, shouldCallPopulate, "Should not call populateVersionInfo when commit is set")
// Values should remain unchanged if we don't call populateVersionInfo
if !shouldCallPopulate {
assert.Equal(t, originalVer, version)
assert.Equal(t, originalCom, commit)
}
})
t.Run("init_logic_when_both_set", func(t *testing.T) {
// Pre-set both values (simulating full build-time injection)
version = "v2.0.0"
commit = "build123"
originalVer := version
originalCom := commit
// The init logic: if version == "" && commit == "" { populateVersionInfo() }
// This should NOT call populateVersionInfo since both are set
shouldCallPopulate := version == "" && commit == ""
assert.False(t, shouldCallPopulate, "Should not call populateVersionInfo when both are set")
// Values should remain unchanged
assert.Equal(t, originalVer, version)
assert.Equal(t, originalCom, commit)
})
}
// TestMainVersionFlag tests the main function's version flag handling logic
func TestMainVersionFlag(t *testing.T) {
// Save original values
originalVersion := version
originalCommit := commit
defer func() {
version = originalVersion
commit = originalCommit
}()
// Set test values
version = "v1.2.3"
commit = "abc123"
tests := []struct {
name string
args []string
shouldExit bool
}{
{
name: "version_long_flag",
args: []string{"teranode", "--version"},
shouldExit: true,
},
{
name: "version_short_flag",
args: []string{"teranode", "-v"},
shouldExit: true,
},
{
name: "version_flag_with_other_args",
args: []string{"teranode", "--config", "test.conf", "--version"},
shouldExit: true,
},
{
name: "no_version_flag",
args: []string{"teranode", "--config", "test.conf"},
shouldExit: false,
},
{
name: "empty_args",
args: []string{"teranode"},
shouldExit: false,
},
{
name: "version_substring_no_match",
args: []string{"teranode", "--my-version"},
shouldExit: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Test the version flag detection logic (extracted from main function)
foundVersionFlag := false
for _, arg := range tt.args[1:] { // Skip program name
if arg == "--version" || arg == "-v" {
foundVersionFlag = true
break
}
}
if tt.shouldExit {
assert.True(t, foundVersionFlag, "Should have found version flag")
// We can't test os.Exit(), but we can test the logic and output format
if foundVersionFlag {
// This is the format that would be printed before os.Exit(0)
expectedOutput := progname + " version " + version + " (commit: " + commit + ")"
assert.Contains(t, expectedOutput, "teranode")
assert.Contains(t, expectedOutput, "v1.2.3")
assert.Contains(t, expectedOutput, "abc123")
}
} else {
assert.False(t, foundVersionFlag, "Should not have found version flag")
// In real main(), this would call teranode.RunDaemon()
}
})
}
}
// TestProgname tests that the program name constant is correct
func TestProgname(t *testing.T) {
assert.Equal(t, "teranode", progname)
}
// TestVersionCommitGlobals tests the global variables
func TestVersionCommitGlobals(t *testing.T) {
// These are package-level variables that can be set at build time
// We test that they exist and can be modified
originalVersion := version
originalCommit := commit
defer func() {
version = originalVersion
commit = originalCommit
}()
// Test that we can set them
version = "test-version"
commit = "test-commit"
assert.Equal(t, "test-version", version)
assert.Equal(t, "test-commit", commit)
// Test they start as strings (even if empty)
version = ""
commit = ""
assert.Equal(t, "", version)
assert.Equal(t, "", commit)
}
// TestPopulateVersionInfoComponents tests individual components of version generation
func TestPopulateVersionInfoComponents(t *testing.T) {
originalVersion := version
originalCommit := commit
defer func() {
version = originalVersion
commit = originalCommit
}()
t.Run("version_format_validation", func(t *testing.T) {
version = ""
commit = ""
populateVersionInfo()
// Test version format
assert.True(t, strings.HasPrefix(version, "v"), "Version should start with 'v'")
// Should have some content
assert.True(t, len(version) > 1, "Version should be more than just 'v'")
assert.True(t, len(commit) > 0, "Commit should not be empty")
// Version should be in one of two formats:
// 1. vX.Y.Z (if git tag exists) - can include suffixes like v1.2.3-beta
// 2. v0.0.0-TIMESTAMP-COMMIT (if no git tag)
if strings.HasPrefix(version, "v0.0.0-") {
// Timestamp-based format (no git tag)
parts := strings.Split(version, "-")
assert.True(t, len(parts) >= 3, "Timestamp-based version should have format v0.0.0-TIMESTAMP-COMMIT")
assert.Equal(t, "v0.0.0", parts[0], "Timestamp-based version should start with v0.0.0")
} else {
// Tag-based format: populateVersionInfo uses `git describe --tags
// --exact-match` and accepts any tag starting with "v", so the version
// is the literal tag name. It need NOT be semver — this repo also uses
// non-semver tags (e.g. v-scaling-test-YYYYMMDD for deploy builds), which
// must not fail this check. Assert the actual contract: a single
// "v"-prefixed token with no whitespace.
assert.Regexp(t, `^v\S+$`, version, "Tag-based version should be a v-prefixed token")
}
})
t.Run("commit_validation", func(t *testing.T) {
version = ""
commit = ""
populateVersionInfo()
// Commit should be either a hash or "unknown"
assert.True(t, len(commit) > 0, "Commit should not be empty")
if commit != "unknown" {
// If it's not "unknown", it should look like a git hash
assert.True(t, len(commit) >= 6, "Git commit hash should be at least 6 characters")
// Git hashes are typically hexadecimal
for _, char := range commit {
assert.True(t,
(char >= '0' && char <= '9') ||
(char >= 'a' && char <= 'f') ||
(char >= 'A' && char <= 'F'),
"Commit hash should be hexadecimal: %s", string(char))
}
}
})
t.Run("timestamp_when_needed", func(t *testing.T) {
version = ""
commit = ""
populateVersionInfo()
// If version contains a timestamp (indicated by having 3 parts separated by -)
if strings.Count(version, "-") >= 2 {
parts := strings.Split(version, "-")
if len(parts) >= 2 {
timestampStr := parts[1]
if len(timestampStr) == 14 { // YYYYMMDDHHMMSS format
parsedTime, err := time.Parse("20060102150405", timestampStr)
if err == nil {
// If we can parse it as a timestamp, verify it's reasonable
// Git timestamps can be arbitrarily old, so we just check:
// 1. Not before project start (2020)
// 2. Not more than 1 hour in the future (allowing for clock skew)
now := time.Now().UTC()
projectStart := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
assert.True(t, parsedTime.After(projectStart),
"Timestamp should be after project start date (got: %v)", parsedTime)
assert.True(t, parsedTime.Before(now.Add(23*time.Hour)),
"Timestamp should not be more than 23 hour in the future (got: %v, now: %v)", parsedTime, now)
t.Logf("Parsed timestamp: %v", parsedTime)
}
}
}
}
})
}
// TestPopulateVersionInfoEdgeCases tests edge cases that are hard to trigger
func TestPopulateVersionInfoEdgeCases(t *testing.T) {
originalVersion := version
originalCommit := commit
defer func() {
version = originalVersion
commit = originalCommit
}()
t.Run("code_structure_documentation", func(t *testing.T) {
// This test documents the structure of populateVersionInfo
// to ensure we understand what branches exist, even if we can't easily test them
version = ""
commit = ""
// The function has several conditional branches:
// 1. git rev-parse command success/failure (lines ~30-34)
// 2. git describe command success/failure (lines ~39-42)
// 3. git tag validation (lines ~46-48)
// 4. git show command success/failure for timestamp (lines ~51-56)
// 5. commit "unknown" check (lines ~59-63)
populateVersionInfo()
// Document what we can verify
assert.NotEmpty(t, version, "Version populated")
assert.NotEmpty(t, commit, "Commit populated")
// The version format tells us which code path was taken
if strings.HasPrefix(version, "v0.0.0-") {
t.Logf("Timestamp-based version generated: %s", version)
parts := strings.Split(version, "-")
if len(parts) >= 3 {
assert.Equal(t, "v0.0.0", parts[0])
t.Logf("Timestamp part: %s", parts[1])
t.Logf("Commit part: %s", parts[2])
}
} else {
t.Logf("Tag-based version generated: %s", version)
assert.True(t, strings.HasPrefix(version, "v"))
}
// Commit is either a hex hash or "unknown"
if commit == "unknown" {
t.Logf("Git commit command failed, using 'unknown'")
} else {
t.Logf("Git commit hash retrieved: %s", commit)
}
})
}
// TestMainFunctionStructure documents the main function logic without executing it
func TestMainFunctionStructure(t *testing.T) {
t.Run("main_function_logic_documentation", func(t *testing.T) {
// This test documents the main() function structure:
// 1. Check for version flags in os.Args[1:]
// 2. If found: print version and os.Exit(0)
// 3. If not found: call teranode.RunDaemon()
// We already tested the version flag logic in TestMainVersionFlag
// The main function itself cannot be easily tested because:
// - os.Exit(0) terminates the program
// - teranode.RunDaemon() starts the actual service
// Document the untested lines:
// Line 67: func main() {
// Line 69: for _, arg := range os.Args[1:] {
// Line 70: if arg == "--version" || arg == "-v" {
// Line 71-72: fmt.Printf + os.Exit(0)
// Line 77: teranode.RunDaemon(progname, version, commit)
assert.Equal(t, "teranode", progname, "Program name used in main()")
// Verify version and commit are accessible for RunDaemon
assert.True(t, len(version) >= 0, "Version variable exists")
assert.True(t, len(commit) >= 0, "Commit variable exists")
})
}