github.com/KEINOS/go-countline@v1.1.1-0.20221217083629-60710df7606b/_example/countline/main_test.go (about) 1 package main 2 3 import ( 4 "os" 5 "path/filepath" 6 "testing" 7 8 "github.com/pkg/errors" 9 "github.com/stretchr/testify/require" 10 "github.com/zenizh/go-capturer" 11 ) 12 13 //nolint:paralleltest // do not parallelize due to temporary changing global variables 14 func Test_main(t *testing.T) { 15 oldOsArgs := os.Args 16 oldOsExit := osExit 17 18 defer func() { 19 os.Args = oldOsArgs 20 osExit = oldOsExit 21 }() 22 23 // Mock os.Exit() to capture the exit code 24 capturedCode := 0 25 osExit = func(code int) { 26 capturedCode = code 27 } 28 29 pathData := filepath.Join("..", "..", "cl", "testdata", "data_Giant.txt") 30 expect := "72323529" 31 32 os.Args = []string{t.Name(), pathData} 33 34 out := capturer.CaptureOutput(func() { 35 main() 36 }) 37 38 require.Contains(t, out, expect, "output should contain the number of lines") 39 require.Equal(t, 0, capturedCode, "exit code should be 0") 40 } 41 42 //nolint:paralleltest // do not parallelize due to temporary changing global variables 43 func Test_main_missing_args(t *testing.T) { 44 oldOsArgs := os.Args 45 oldOsExit := osExit 46 47 defer func() { 48 os.Args = oldOsArgs 49 osExit = oldOsExit 50 }() 51 52 // Mock os.Exit() to capture the exit code and panic instead of exiting 53 capturedCode := 0 54 osExit = func(code int) { 55 capturedCode = code 56 57 panic("forced panic") 58 } 59 60 os.Args = []string{t.Name()} 61 62 out := capturer.CaptureStderr(func() { 63 require.Panics(t, func() { 64 main() 65 }) 66 }) 67 68 require.Contains(t, out, "Count the number of lines in a file", 69 "STDERR should contain the help message on error") 70 require.Contains(t, out, "error: invalid number of arguments", 71 "STDERR should contain the error reason") 72 require.Equal(t, 1, capturedCode, "exit code should be 1 on error") 73 } 74 75 //nolint:paralleltest // do not parallelize due to temporary changing global variables 76 func TestExitOnError(t *testing.T) { 77 oldOsExit := osExit 78 defer func() { 79 osExit = oldOsExit 80 }() 81 82 // Mock os.Exit() to capture the exit code 83 capturedCode := 0 84 osExit = func(code int) { 85 capturedCode = code 86 } 87 88 out := capturer.CaptureStderr(func() { 89 ExitOnError(errors.New("test error")) 90 }) 91 92 require.Equal(t, 1, capturedCode, "exit code should be 1") 93 require.Contains(t, out, "error: test error", "error reason should be printed to STDERR") 94 require.Contains(t, out, "Usage:", "help should be printed on error") 95 }