Skip to content

Commit

Permalink
Add config option to colorize errors in std out
Browse files Browse the repository at this point in the history
  • Loading branch information
Stein Fletcher committed May 15, 2021
1 parent da596bb commit 503426c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
9 changes: 8 additions & 1 deletion apitest.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ type APITest struct {
debugEnabled bool
mockResponseDelayEnabled bool
networkingEnabled bool
colorizeErrors bool
networkingHTTPClient *http.Client
reporter ReportFormatter
verifier Verifier
Expand Down Expand Up @@ -129,6 +130,12 @@ func (a *APITest) Debug() *APITest {
return a
}

// ColorizeErrors configures the error reporter to show messages in red. Disabled on windows
func (a *APITest) ColorizeErrors() *APITest {
a.colorizeErrors = true
return a
}

// Report provides a hook to add custom formatting to the output of the test
func (a *APITest) Report(reporter ReportFormatter) *APITest {
a.reporter = reporter
Expand Down Expand Up @@ -800,7 +807,7 @@ func (r *Response) runTest() *http.Response {
}()

if a.verifier == nil {
a.verifier = DefaultVerifier{}
a.verifier = DefaultVerifier{ColorizeErrors: a.colorizeErrors}
}

a.assertMocks()
Expand Down
13 changes: 11 additions & 2 deletions assert.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ type Verifier interface {
}

// DefaultVerifier is a verifier that uses some code from https://github.com/stretchr/testify to perform assertions
type DefaultVerifier struct{}
type DefaultVerifier struct {
ColorizeErrors bool
}

var _ Verifier = DefaultVerifier{}

Expand Down Expand Up @@ -77,6 +79,13 @@ func (a DefaultVerifier) Equal(t TestingT, expected, actual interface{}, msgAndA
return true
}

func (a DefaultVerifier) colorize(message string) string {
if runtime.GOOS == "windows" || !a.ColorizeErrors {
return message
}
return "\033[0m" + message + "\033[31m"
}

// Fail reports a failure
func (a DefaultVerifier) Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
content := []labeledContent{
Expand All @@ -96,7 +105,7 @@ func (a DefaultVerifier) Fail(t TestingT, failureMessage string, msgAndArgs ...i
content = append(content, labeledContent{"Messages", message})
}

t.Errorf("\n%s", ""+labeledOutput(content...))
t.Errorf("\n%s", ""+a.colorize(labeledOutput(content...)))

return false
}
Expand Down

0 comments on commit 503426c

Please sign in to comment.