Last active
December 5, 2024 06:22
-
-
Save yakuter/8bc267237300c6dafdcdce3ca0ae7f22 to your computer and use it in GitHub Desktop.
Testing Exit, Fatal, and Panic in Golang 1/3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"os" | |
"testing" | |
) | |
func TestExit(t *testing.T) { | |
// Save the original os.Exit | |
originalExit := os.Exit | |
defer func() { os.Exit = originalExit }() | |
exitCalled := false | |
exitCode := 0 | |
// Mock os.Exit | |
os.Exit = func(code int) { | |
exitCalled = true | |
exitCode = code | |
panic("os.Exit called") // Prevent actual exit | |
} | |
// Capture stdout | |
var buf bytes.Buffer | |
originalStdout := os.Stdout | |
r, w, _ := os.Pipe() | |
os.Stdout = w | |
defer func() { os.Stdout = originalStdout }() | |
// Test the function | |
func() { | |
defer func() { | |
recover() // Catch panic | |
w.Close() | |
}() | |
logAndExit("Critical error occurred") | |
}() | |
// Read output | |
io.Copy(&buf, r) | |
// Verify exit behavior | |
if !exitCalled { | |
t.Errorf("os.Exit was not called") | |
} | |
if exitCode != 1 { | |
t.Errorf("Expected exit code 1, got %d", exitCode) | |
} | |
if buf.String() != "Critical error occurred\n" { | |
t.Errorf("Unexpected output: %s", buf.String()) | |
} | |
} | |
func logAndExit(message string) { | |
fmt.Println(message) | |
os.Exit(1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment