@@ -2,14 +2,15 @@ package toolkit
22
33import (
44 "context"
5+ "fmt"
56 "log"
67 "testing"
78)
89
910// testLoggerKey is a private key to prevent *testing.T from being easily accessed
1011type testLoggerKey struct {}
1112
12- func ContextWithT (ctx context.Context , t * testing.T ) context.Context {
13+ func ContextWithT (ctx context.Context , t testing.TB ) context.Context {
1314 if t == nil {
1415 log .Println ("WARNING: No *testing.T provided, this function should only be called from a test" )
1516 return ctx
@@ -18,7 +19,7 @@ func ContextWithT(ctx context.Context, t *testing.T) context.Context {
1819}
1920
2021func Logf (ctx context.Context , format string , args ... any ) {
21- t , ok := ctx .Value (testLoggerKey {}).(* testing.T )
22+ t , ok := ctx .Value (testLoggerKey {}).(testing.TB )
2223 if ! ok || t == nil {
2324 log .Printf (format + "WARNING: No *testing.T in Context, this function should only be called from " , args ... )
2425 }
@@ -27,11 +28,68 @@ func Logf(ctx context.Context, format string, args ...any) {
2728}
2829
2930func Log (ctx context.Context , args ... any ) {
30- t , ok := ctx .Value (testLoggerKey {}).(* testing.T )
31+ t , ok := ctx .Value (testLoggerKey {}).(testing.TB )
3132 if ! ok || t == nil {
3233 log .Println ("WARNING: No *testing.T in Context, this function should only be called from a test" )
3334 return
3435 }
3536 t .Helper ()
3637 t .Log (args ... )
3738}
39+
40+ type testLogger struct {
41+ testing.TB
42+ }
43+
44+ // formatError formats the ERROR prefix with emoji
45+ func (t * testLogger ) formatError () string {
46+ return "🔴 FAIL:"
47+ }
48+
49+ func (t * testLogger ) Fatal (args ... any ) {
50+ t .Helper ()
51+ // Prepend "ERROR: " to the first argument
52+ if len (args ) > 0 {
53+ args [0 ] = fmt .Sprintf ("%s %v" , t .formatError (), args [0 ])
54+ } else {
55+ args = []any {t .formatError () + " " }
56+ }
57+ t .TB .Fatal (args ... )
58+ }
59+
60+ func (t * testLogger ) Fatalf (format string , args ... any ) {
61+ t .Helper ()
62+ t .TB .Fatalf (t .formatError ()+ " " + format , args ... )
63+ }
64+
65+ func (t * testLogger ) Error (args ... any ) {
66+ t .Helper ()
67+ // Prepend "ERROR: " to the first argument
68+ if len (args ) > 0 {
69+ args [0 ] = fmt .Sprintf ("%s %v" , t .formatError (), args [0 ])
70+ } else {
71+ args = []any {t .formatError () + " " }
72+ }
73+ t .TB .Error (args ... )
74+ }
75+
76+ func (t * testLogger ) Errorf (format string , args ... any ) {
77+ t .Helper ()
78+ t .TB .Errorf (t .formatError ()+ " " + format , args ... )
79+ }
80+
81+ func (t * testLogger ) FailNow () {
82+ t .Helper ()
83+ t .Log (t .formatError ())
84+ t .TB .FailNow ()
85+ }
86+
87+ func (t * testLogger ) Fail () {
88+ t .Helper ()
89+ t .Log (t .formatError ())
90+ t .TB .Fail ()
91+ }
92+
93+ func WithTestLogger (t testing.TB ) testing.TB {
94+ return & testLogger {TB : t }
95+ }
0 commit comments