-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
79 lines (63 loc) · 1.61 KB
/
main_test.go
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
package main
import (
"fmt"
"os"
"strings"
"testing"
"github.com/nszilard/slack/cmd"
)
func captureOutput(t *testing.T, f func(), name string) string {
t.Helper()
// Create and remove capture file
captured, err := os.Create(name + ".log")
if err != nil {
t.Fatalf("error creating capture file: %v", err)
}
defer os.Remove(captured.Name())
// Redirecting output
stdout := os.Stdout
os.Stdout = captured
// Call function
f()
// Reset output
os.Stdout = stdout
// Read captured data
data, err := os.ReadFile(captured.Name())
if err != nil {
t.Fatalf("failed to read capture file: %v", err)
}
// Return as string
return strings.TrimSpace(string(data))
}
//-------------------------------------------
// Mocks
//-------------------------------------------
func fakeExit(int) {
fmt.Println("os.Exit(1)")
}
func fakeExecute() error {
return fmt.Errorf("some error")
}
//-------------------------------------------
// Tests
//-------------------------------------------
func TestMain(t *testing.T) {
expected := "A simple CLI tool to send Slack messages programmatically using pre-defined templates."
actual := captureOutput(t, main, "main_test.log")
if !strings.HasPrefix(actual, expected) {
t.Errorf("main: unexpected output for root command")
}
}
func TestMainError(t *testing.T) {
exit = fakeExit
executeRootCommand = fakeExecute
defer func() {
exit = os.Exit
executeRootCommand = cmd.Execute
}()
expected := "os.Exit(1)"
actual := captureOutput(t, main, "main_test_error.log")
if !strings.HasPrefix(actual, expected) {
t.Errorf("main: unexpected error output for root command")
}
}