stonelog/log_test.go
Rene Nochebuena a7c6a85084
All checks were successful
Go CI/CD / go-ci (push) Successful in 10m8s
Go CI/CD / go-ci (pull_request) Successful in 10m12s
Refactor test binary location and update sonar exclusions
Moved the test binary from "tests" to "testbin" for better organization. Updated `sonar-project.properties` to exclude the new directory from analysis and adjusted test references accordingly.
2025-04-10 10:57:51 -06:00

115 lines
2.3 KiB
Go

package stonelog
import (
"errors"
"os/exec"
"testing"
)
func Test_LogLevelString(t *testing.T) {
levelTests := []struct {
level StoneLevel
expected string
}{
{TRACE, "TRACE"},
{DEBUG, "DEBUG"},
{INFO, "INFO"},
{WARN, "WARN"},
{ERROR, "ERROR"},
{FATAL, "FATAL"},
{PANIC, "PANIC"},
}
for _, tt := range levelTests {
if tt.level.String() != tt.expected {
t.Errorf("Expected %s, got %s", tt.expected, tt.level.String())
}
}
}
func Test_LogLevelColor(t *testing.T) {
levelTests := []struct {
level StoneLevel
expected string
}{
{TRACE, colorWhite},
{DEBUG, colorCyan},
{INFO, colorGreen},
{WARN, colorYellow},
{ERROR, colorRed},
{FATAL, colorMagenta},
{PANIC, colorRed + "\033[1m"},
}
for _, tt := range levelTests {
if tt.level.Color() != tt.expected {
t.Errorf("Expected %s, got %s", tt.expected, tt.level.Color())
}
}
}
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")
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_MutedPlainTextLogs(t *testing.T) {
InitStoneLog(ERROR, false, true)
// This won't change the log level
SetLogLevel(-1)
// Following won't appear
Trace("This is a trace log")
Debug("This is a debug log")
Observation("This is an observation log")
Hypothesis("This is a hypothesis log")
// Until this one
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)
}
}()
InitStoneLog(TRACE, false, true)
Panic("This is a panic log")
}
func Test_FatalPlainTextLogs(t *testing.T) {
cmd := exec.Command(
"go", "run", "./testbin/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())
}
}
}