-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
620 lines (532 loc) · 18.1 KB
/
main_test.go
File metadata and controls
620 lines (532 loc) · 18.1 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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
// P4GoForge
/*
_____ _ _ _____ ______
| __ \| || | / ____| | ____|
| |__) | || |_| | __ ___ | |__ ___ _ __ __ _ ___
| ___/|__ _| | |_ |/ _ \| __/ _ \| '__/ _` |/ _ \
| | | | | |__| | (_) | | | (_) | | | (_| | __/
|_| |_| \_____|\___/|_| \___/|_| \__, |\___|
__/ |
|___/
*/
// TODO Clean up these ugly ugly variables
// TODO better enviroment variable handling
// TOOD fix pathings
/*
How to send a string of p4 commands
commands := []string{
"info",
"configure show allservers",
"groups",
"users -a",
}
output, err := P4Commands(p4Test, commands, DefaultP4Config) <-- DefaultP4Config or BrokerP4Config (See test_functions.go for more details)
*/
package main
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
// Other necessary imports...
)
var loadBroker = true
var BrokerDebug = false
var loadCheckPoint = false
var startDir string
var binDir string
var p4payloadDir string
var checkPointfile string
var newPath string
var originalEnvVars map[string]string
var wd string
func init() {
fmt.Println(coloredOutput(colorBlue, "THIS IS SPARTA"))
// Initialize global variables here
var err error
wd, err = os.Getwd()
if err != nil {
fmt.Println("Error getting current working directory:", err)
os.Exit(1)
}
fmt.Printf("wd = %s\n", wd)
// Save the current environment variables
originalEnvVars = make(map[string]string)
for _, env := range os.Environ() {
pair := strings.SplitN(env, "=", 2)
if len(pair) == 2 {
originalEnvVars[pair[0]] = pair[1]
}
}
/*
fmt.Println(coloredOutput(colorBlue, "THIS IS SPARTA"))
// Save the current environment variables
originalEnvVars = make(map[string]string)
for _, env := range os.Environ() {
pair := strings.SplitN(env, "=", 2)
if len(pair) == 2 {
originalEnvVars[pair[0]] = pair[1]
}
}
// Initialize global variables here
wd, err := os.Getwd()
if err != nil {
fmt.Println("Error getting current working directory:", err)
os.Exit(1)
}
startDir = filepath.Join(wd, "tmp")
binDir = filepath.Join(wd, "bin")
p4payloadDir = filepath.Join(wd, "p4payload")
checkPointfile = "zaplock-payload.ckp.8"
originalPath := os.Getenv("PATH")
newPath := fmt.Sprintf("%s:%s", originalPath, binDir)
os.Setenv("PATH", newPath)
if err := checkBinaries(); err != nil {
fmt.Println(err)
os.Exit(1)
}
*/
}
type P4Test struct {
startDir string
binDir string
p4payloadDir string
checkPointfile string
p4d string
p4 string
p4broker string
port string
bport string
testRoot string
serverRoot string
serverPort string
brokerPort string
serverLog string
brokerRoot string
clientRoot string
p4Passwd string
rshp4dCommand string
rshp4brokerCommand string
p4dProcess *os.Process
p4brokerProcess *os.Process
}
func makeP4Test(startDir string) *P4Test {
fmt.Println(coloredOutput(colorBlue, "makeP4Test"))
/*
// Save the current environment variables
originalEnvVars = make(map[string]string)
for _, env := range os.Environ() {
pair := strings.SplitN(env, "=", 2)
if len(pair) == 2 {
originalEnvVars[pair[0]] = pair[1]
}
}
*/
startDir = filepath.Join(wd, "tmp")
binDir = filepath.Join(wd, "bin")
p4payloadDir = filepath.Join(wd, "p4payload")
checkPointfile = "zaplock-payload.ckp.8"
originalPath := os.Getenv("PATH")
newPath := fmt.Sprintf("%s:%s", originalPath, binDir)
os.Setenv("PATH", newPath)
if err := checkBinaries(); err != nil {
fmt.Println(err)
os.Exit(1)
}
os.Setenv("P4CONFIG", ".p4config")
p4t := &P4Test{
startDir: startDir,
binDir: binDir,
p4payloadDir: p4payloadDir,
}
// Now p4t is fully defined, initialize the other fields
p4t.testRoot = filepath.Join(p4t.startDir, "testroot")
p4t.serverRoot = filepath.Join(p4t.testRoot, "server")
p4t.serverLog = filepath.Join(p4t.testRoot, "server-log/log")
p4t.brokerRoot = filepath.Join(p4t.testRoot, "broker")
p4t.clientRoot = filepath.Join(p4t.testRoot, "client")
p4t.checkPointfile = filepath.Join(p4t.p4payloadDir, "/", checkPointfile)
p4t.p4Passwd = "perforce"
p4t.ensureDirectories()
p4t.p4d = filepath.Join(p4t.binDir, "p4d")
p4t.p4 = filepath.Join(p4t.binDir, "p4")
p4t.p4broker = filepath.Join(p4t.binDir, "p4broker")
p4t.bport = fmt.Sprintf("rsh:%s -c %s -q", p4t.p4broker, p4t.brokerRoot+"/p4broker.cfg")
p4t.port = fmt.Sprintf("rsh:%s -r %s -L %s", p4t.p4d, p4t.serverRoot, p4t.serverLog)
//os.Chdir(p4t.clientRoot)
return p4t
}
// setupTestEnv initializes the Perforce server environment for testing.
func setupTestEnv(t *testing.T) *P4Test {
fmt.Println(coloredOutput(colorBlue, "setupTestEnv"))
// Create the P4Test instance first
p4Test := makeP4Test(startDir)
// Now set the environment variables using p4Test
setP4Config(DefaultP4Config, p4Test)
t.Log("Test environment set up successfully")
if err := startP4dDaemon(p4Test); err != nil {
t.Fatalf("Failed to start p4d: %v", err)
}
t.Log("p4d started successfully")
p4Test.rshp4dCommand = fmt.Sprintf(`"rsh:%s -r %s -L %s -d -q"`, p4Test.p4d, p4Test.serverRoot, p4Test.serverLog)
if loadBroker {
if err := setupP4Broker(p4Test); err != nil {
t.Fatalf("Broker setup failed: %v", err)
}
t.Log("p4broker started successfully")
}
os.Setenv("P4USER", "perforce")
////// CREATE USERS
// Create Users
users := []string{"user1", "user2", "user3", "user4", "user5"}
for _, user := range users {
if err := createUser(p4Test, user); err != nil {
t.Fatalf("Error creating user %s: %v", user, err)
}
if err := createWorkspace(p4Test, user); err != nil {
t.Fatalf("Error creating user %s: %v", user, err)
}
}
// Create the group and add specified users to it.
// Define the users to be added to the AuthorizedUser-ZapLock group
authorizedUsers := []string{"user1", "user3", "user5"}
// Create the group and add specified users to it
if err := createGroup(p4Test, "AuthorizedUser-ZapLock", authorizedUsers); err != nil {
t.Fatalf("Error creating group AuthorizedUser-ZapLock: %v", err)
}
//TODO move this probaly
type FileDetails struct {
FileType string
UserName string
MLockfile bool
}
filesToCreate := map[string]FileDetails{
"eLOCKtextfile1.txt": {FileType: "text+lmx", UserName: "user1", MLockfile: false},
"eLOCKtextfile2.txt": {FileType: "text+lm", UserName: "user1", MLockfile: false},
"mLOCKbinaryfile1.bin": {FileType: "binary", UserName: "user1", MLockfile: true},
"mLOCKtextfile2.txt": {FileType: "text", UserName: "user5", MLockfile: true},
"mLOCKtextfile3.txt": {FileType: "text+ml", UserName: "user5", MLockfile: true},
"eLOCKtextfile3.txt": {FileType: "text+l", UserName: "user5", MLockfile: false},
"eLOCKbinaryfile2.bin": {FileType: "binary+klm", UserName: "user5", MLockfile: true},
"eLOCKbinaryfile3.bin": {FileType: "binary+ml", UserName: "user5", MLockfile: true},
}
////////////////////user2 is not in the group
/*
filesToCreate := map[string]string{
"textfile1.txt": "text+lmx",
"binaryfile1.bin": "binary",
"textfile2.txt": "text",
"textfile3.txt": "text+l",
"binaryfile2.bin": "binary+klm",
}
*/
/*
if err := createDepotFiles(p4Test, "user1", filesToCreate); err != nil {
t.Fatalf("Error creating and adding files to depot: %v", err)
}*/
for fileName, details := range filesToCreate {
if err := createDepotFiles(p4Test, details.UserName, map[string]string{fileName: details.FileType}); err != nil {
t.Fatalf("Error creating and adding file %s to depot by user %s: %v", fileName, details.UserName, err)
}
}
// Sync workspaces and create changelists for each user
for _, user := range users {
if err := syncUserWorkspace(p4Test, user); err != nil {
t.Fatalf("Error syncing workspace for user %s: %v", user, err)
}
changelistNumber, err := createChangelist(p4Test, user)
if err != nil {
t.Fatalf("Error creating changelist for user %s: %v", user, err)
}
// Log or do something with the changelist number
fmt.Printf("Changelist for user %s created: %s\n", user, changelistNumber)
// Check out files associated with this user to their changelist
for fileName, details := range filesToCreate {
if details.UserName == user {
fmt.Printf("Checking out file: %s, User: %s, Changelist: %s\n", fileName, user, changelistNumber)
// Uncomment below line to actually execute the function after dry run
if err := checkoutFilesToChangelist(p4Test, user, fileName, changelistNumber, details.MLockfile); err != nil {
t.Fatalf("Error checking out file %s to changelist %s by user %s: %v", fileName, changelistNumber, user, err)
}
}
}
}
/*filesToLock := []string{"textfile1.txt", "textfile2.txt"}
usersToLockFiles := []string{"user2", "user4"}
for _, user := range usersToLockFiles {
if err := checkoutAndLockFiles(p4Test, user, filesToLock); err != nil {
t.Fatalf("Error checking out and locking files for user %s: %v", user, err)
}
}
*/
/*
errUser2 := checkoutAndLockFiles(p4Test, "user2", []string{"textfile1.txt", "textfile2.txt"})
if errUser2 != nil {
t.Fatalf("Error checking out and locking files for user2: %v", errUser2)
}
errUser4 := checkoutAndLockFiles(p4Test, "user4", []string{"textfile1.txt", "textfile2.txt"})
if errUser4 != nil {
t.Fatalf("Error checking out and locking files for user4: %v", errUser4)
}
*/
return p4Test
}
func startP4dDaemon(p4t *P4Test) error {
fmt.Println(coloredOutput(colorBlue, "startP4dDaemon"))
if loadCheckPoint {
// Load checkpoint
output, err := P4dCommand(true, "-r", p4t.serverRoot, "-L", p4t.serverLog, "-jr", p4t.checkPointfile)
fmt.Printf("Load checkpoint output: %s\n", output)
if err != nil {
return fmt.Errorf("failed to load checkpoint: %v", err)
}
fmt.Println("Checkpoint loaded successfully.")
// Update the database
output, err = P4dCommand(true, "-r", p4t.serverRoot, "-L", p4t.serverLog, "-xu")
fmt.Printf("Update database output: %s\n", output)
if err != nil {
return fmt.Errorf("failed to update db: %v", err)
}
fmt.Println("Database updated successfully.")
}
// Start p4d using rsh
p4dCmd := exec.Command(filepath.Join(p4t.binDir, "p4d"), "-r", p4t.serverRoot, "-L", p4t.serverLog, "-vserver=3 -d -q")
if err := p4dCmd.Start(); err != nil {
return fmt.Errorf("failed to start p4d: %v", err)
}
p4t.p4dProcess = p4dCmd.Process
return nil
}
func startP4broker(p4t *P4Test) error {
fmt.Println(coloredOutput(colorBlue, "startP4broker"))
// Construct the command
rshCommand := fmt.Sprintf("%s -c %s -d", p4t.p4broker, p4t.brokerRoot+"/p4broker.cfg")
// Split the command into executable and arguments
cmdParts := strings.Fields(rshCommand)
cmd := exec.Command(cmdParts[0], cmdParts[1:]...)
// Declare the buffers outside the if statement
var stdoutBuf, stderrBuf bytes.Buffer
if BrokerDebug {
// Assign the buffers for capturing output
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
}
// Start the command
if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to start p4broker with rsh: %v", err)
}
// Wait for the command to finish if debugging is enabled
if BrokerDebug {
if err := cmd.Wait(); err != nil {
// Capture and print output if there is an error
stdoutStr, stderrStr := stdoutBuf.String(), stderrBuf.String()
fmt.Printf("p4broker STDOUT:\n%s\n", stdoutStr)
fmt.Printf("p4broker STDERR:\n%s\n", stderrStr)
return fmt.Errorf("p4broker command failed: %v", err)
}
}
// Store the process for later cleanup
p4t.p4brokerProcess = cmd.Process
return nil
}
func teardownTestEnv(t *testing.T, p4t *P4Test) {
fmt.Println(coloredOutput(colorRed, "teardownTestEnv"))
fmt.Printf("Working Dir %s\n", wd)
// Terminate p4d process
if p4t.p4dProcess != nil {
if err := p4t.p4dProcess.Kill(); err != nil {
fmt.Printf("Failed to kill p4d process: %v\n", err)
} else {
fmt.Printf("p4d process terminated successfully\n")
}
}
// Terminate p4broker process
if p4t.p4brokerProcess != nil {
if err := p4t.p4brokerProcess.Kill(); err != nil {
fmt.Printf("Failed to kill p4broker process: %v\n", err)
} else {
fmt.Printf("p4broker process terminated successfully\n")
}
}
// Clear environment variables and restore original ones
os.Clearenv()
for key, value := range originalEnvVars {
if err := os.Setenv(key, value); err != nil {
fmt.Printf("Failed to restore environment variable %s: %v\n", key, err)
} else {
//fmt.Printf("Restored environment variable %s successfully\n", key)
}
}
// Remove the test directory
rmCmd := fmt.Sprintf("rm -rvf %s", p4t.testRoot)
//rmCmd := fmt.Sprintf("woof woof")
if err := exec.Command("bash", "-c", rmCmd).Run(); err != nil {
fmt.Printf("Failed to remove test directory: %v\n", err)
} else {
fmt.Printf("Test directory removed successfully\n")
}
// Check if test directory is empty
isEmpty, err := isDirectoryEmpty(p4t.testRoot)
if err != nil {
fmt.Printf("checking if test directory is empty or exists: %v\n", err)
} else if isEmpty {
fmt.Printf("Test directory is empty\n")
} else {
fmt.Printf("Test directory is not empty\n")
}
fmt.Println(coloredOutput(colorRed, "teardownTestEnv complete"))
// Log environment variables after teardown
logEnvironmentVariables("Environment Variables After Teardown\n")
}
func buildp4dTestEnv(t *testing.T, p4t *P4Test) {
fmt.Printf("Building p4d depots and suchs\n")
// The needful commands
}
func TestP4OGCommands(t *testing.T) {
logEnvironmentVariables("Environment Variables Before Setup")
funcName := getFunctionName()
fmt.Println(coloredOutput(colorPurple, funcName))
p4Test := setupTestEnv(t) // Setup test environment
defer teardownTestEnv(t, p4Test) // Teardown test environment
commands := []string{
"info",
"configure show allservers",
"groups",
"users -a",
"clients",
"depots",
"files //...",
"changes",
"describe 1",
//"fstat //...",
"group -o AuthorizedUser-ZapLock",
}
output, err := P4Commands(p4Test, commands, DefaultP4Config)
if err != nil {
t.Fatalf("Error executing p4 commands: %v", err)
}
logEnvironmentVariables("Environment Variables During Setup")
fmt.Println("Output of p4 commands:\n", output)
}
func TestP4OGBrokerCommands(t *testing.T) {
funcName := getFunctionName()
fmt.Println(coloredOutput(colorPurple, funcName))
p4Test := setupTestEnv(t) // Setup test environment
defer teardownTestEnv(t, p4Test) // Teardown test environment
commands := []string{
"info",
"configure show allservers",
"groups",
"users -a",
"clients",
"depots",
"files //...",
"changes",
"fstat //...",
"describe 1",
//"group -o AuthorizedUser-ZapLock",
}
output, err := P4Commands(p4Test, commands, BrokerP4Config)
if err != nil {
t.Fatalf("Error executing p4 commands: %v", err)
}
fmt.Println("Output of p4 commands:\n", output)
}
func TestP4OGZaplockHelpCommands(t *testing.T) {
funcName := getFunctionName()
fmt.Println(coloredOutput(colorPurple, funcName))
p4Test := setupTestEnv(t) // Setup test environment
defer teardownTestEnv(t, p4Test) // Teardown test environment
commands := []string{
"zaplock -h",
}
output, err := P4Commands(p4Test, commands, BrokerP4Config)
if err != nil {
t.Fatalf("Error executing p4 commands: %v", err)
}
fmt.Println("Output of p4 commands:\n", output)
}
func TestP4OGZaplockCCommandsNONAUTH(t *testing.T) {
funcName := getFunctionName()
fmt.Println(coloredOutput(colorPurple, funcName))
p4Test := setupTestEnv(t) // Setup test environment
defer teardownTestEnv(t, p4Test) // Teardown test environment
commands := []string{
"zaplock -c 9 -L -M -y",
}
os.Setenv("P4USER", "user2")
output, err := P4Commands(p4Test, commands, BrokerP4Config)
if err != nil {
t.Fatalf("Error executing p4 commands: %v", err)
}
fmt.Println("Output of p4 commands:\n", output)
}
func TestP4OGZaplockCCommandsAUTH(t *testing.T) {
funcName := getFunctionName()
fmt.Println(coloredOutput(colorPurple, funcName))
p4Test := setupTestEnv(t) // Setup test environment
defer teardownTestEnv(t, p4Test) // Teardown test environment
commands := []string{
"zaplock -c 9 -L -M -y",
}
os.Setenv("P4USER", "user3")
output, err := P4Commands(p4Test, commands, BrokerP4Config)
if err != nil {
t.Fatalf("Error executing p4 commands: %v", err)
}
fmt.Println("Output of p4 commands:\n", output)
}
func TestP4OGZaplockCCommandsAUTHargL(t *testing.T) {
funcName := getFunctionName()
fmt.Println(coloredOutput(colorPurple, funcName))
p4Test := setupTestEnv(t) // Setup test environment
defer teardownTestEnv(t, p4Test) // Teardown test environment
commands := []string{
"zaplock -c 9 -L -y",
}
os.Setenv("P4USER", "user3")
output, err := P4Commands(p4Test, commands, BrokerP4Config)
if err != nil {
t.Fatalf("Error executing p4 commands: %v", err)
}
fmt.Println("Output of p4 commands:\n", output)
}
func TestP4OGZaplockCCommandsAUTHargM(t *testing.T) {
funcName := getFunctionName()
fmt.Println(coloredOutput(colorPurple, funcName))
p4Test := setupTestEnv(t) // Setup test environment
defer teardownTestEnv(t, p4Test) // Teardown test environment
commands := []string{
"zaplock -c 9 -M -y",
}
os.Setenv("P4USER", "user3")
output, err := P4Commands(p4Test, commands, BrokerP4Config)
if err != nil {
t.Fatalf("Error executing p4 commands: %v", err)
}
fmt.Println("Output of p4 commands:\n", output)
}
func TestP4OGZaplockCCommandsAUTHwrongauth(t *testing.T) {
funcName := getFunctionName()
fmt.Println(coloredOutput(colorPurple, funcName))
p4Test := setupTestEnv(t) // Setup test environment
defer teardownTestEnv(t, p4Test) // Teardown test environment
commands := []string{
"zaplock -c 9 -L -M -y 1234",
}
os.Setenv("P4USER", "user3")
output, err := P4Commands(p4Test, commands, BrokerP4Config)
// Check if the error is the expected one
expectedError := "Incorrect or expired confirmation code"
if err != nil && strings.Contains(err.Error(), expectedError) {
fmt.Println("Received the expected error:", err)
} else if err != nil {
t.Fatalf("Unexpected error executing p4 commands: %v", err)
} else {
t.Fatalf("Expected an error, but none occurred")
}
fmt.Println("Output of p4 commands:\n", output)
}