From d126d4ef7ab3f3f3957a0aabcbe2d7d2f8660868 Mon Sep 17 00:00:00 2001 From: Rene Nochebuena Date: Thu, 10 Apr 2025 10:48:34 -0600 Subject: [PATCH] Add tests for panic and fatal log handling Introduce tests for handling panic and fatal log scenarios, including recovery from panics and execution of external processes to test fatal behavior. Adjusted logging levels and prefixes to ensure consistency for PANIC logs. --- log.go | 1 + log_test.go | 45 +++++++++++++++++++++++++++++++++++++-------- tests/main.go | 14 ++++++++++++++ 3 files changed, 52 insertions(+), 8 deletions(-) create mode 100644 tests/main.go diff --git a/log.go b/log.go index c4516e2..dbbe934 100644 --- a/log.go +++ b/log.go @@ -223,6 +223,7 @@ func getRandomPrefix(level StoneLevel) string { WARN: stoneWarnPrefixes, ERROR: stoneErrorPrefixes, FATAL: stonePanicPrefixes, + PANIC: stonePanicPrefixes, } prefixes := prefixMap[level] diff --git a/log_test.go b/log_test.go index 026ee90..a744ad9 100644 --- a/log_test.go +++ b/log_test.go @@ -1,6 +1,8 @@ package stonelog import ( + "errors" + "os/exec" "testing" ) @@ -46,6 +48,17 @@ func Test_LogLevelColor(t *testing.T) { } } +func Test_JSONLogs(t *testing.T) { + InitStoneLog(TRACE, true, false) + Trace("This is a trace log") + Debug("This is a debug log") + Observation("This is an observation log") + Hypothesis("This is a hypothesis log") + Failure("This is a failure log") + + SetLogLevel(INFO) +} + func Test_PlainTextLogs(t *testing.T) { InitStoneLog(TRACE, false, false) Trace("This is a trace log") @@ -73,13 +86,29 @@ func Test_MutedPlainTextLogs(t *testing.T) { Failure("This is a failure log") } -func Test_JSONLogs(t *testing.T) { - InitStoneLog(TRACE, true, false) - Trace("This is a trace log") - Debug("This is a debug log") - Observation("This is an observation log") - Hypothesis("This is a hypothesis log") - Failure("This is a failure log") +func Test_PanicPlainTextLogs(t *testing.T) { + defer func() { + if r := recover(); r != nil { + Observation("Recovered from panic: %v", r) + } + }() - SetLogLevel(INFO) + InitStoneLog(TRACE, false, true) + Panic("This is a panic log") +} + +func Test_FatalPlainTextLogs(t *testing.T) { + cmd := exec.Command( + "go", "run", "./test/main.go", + ) + cmd.Env = append(cmd.Env, "TEST_FATAL=1") + + err := cmd.Run() + + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + if exitErr.ExitCode() != 1 { + t.Errorf("Expected exit code 1, got %d", exitErr.ExitCode()) + } + } } diff --git a/tests/main.go b/tests/main.go new file mode 100644 index 0000000..d51eccb --- /dev/null +++ b/tests/main.go @@ -0,0 +1,14 @@ +package main + +import ( + "os" + + "gitstormr.dev/stone-utils/stonelog" +) + +func main() { + if os.Getenv("TEST_FATAL") == "1" { + stonelog.InitStoneLog(stonelog.TRACE, false, false) + stonelog.Meltdown("A fatal error occurred") + } +}