1
0
Assert/errors.go

59 lines
1.4 KiB
Go

package assert
import (
"fmt"
"path/filepath"
"runtime"
"strings"
)
const messageFormat = `
%s:%d
assert.%s
Expected: %v
Actual: %v
`
const singleValueFormat = `
%s:%d
assert.%s
Value: %v
`
// fileInfo returns file and line information for the test caller
func fileInfo() (string, int) {
// Skip frames: runtime.Callers, this function, assertion function, and test helper
// This gets us to the actual test file that called the assertion
const skip = 3
_, file, line, ok := runtime.Caller(skip)
if !ok {
return "unknown_file", 0
}
// Extract just the filename without the full path
fileName := filepath.Base(file)
// If we're still not in a test file, search up the stack
if !strings.Contains(fileName, "_test.go") {
// Try one more frame up
_, file, line, ok = runtime.Caller(skip + 1)
if ok {
fileName = filepath.Base(file)
}
}
return fileName, line
}
// formatMessage formats an error message with the file location
func formatMessage(methodName string, expected, actual any) string {
file, line := fileInfo()
return fmt.Sprintf(messageFormat, file, line, methodName, expected, actual)
}
// formatSingleValueMessage formats an error message for single-value assertions
func formatSingleValueMessage(methodName string, value any) string {
file, line := fileInfo()
return fmt.Sprintf(singleValueFormat, file, line, methodName, value)
}