Suppress printing the internals of context.Context. Added a flag to override this behaviour.
diff --git a/format/format.go b/format/format.go
index 952726e..8fde56b 100644
--- a/format/format.go
+++ b/format/format.go
@@ -4,6 +4,7 @@
package format
import (
+ "context"
"fmt"
"reflect"
"strconv"
@@ -22,6 +23,14 @@
*/
var UseStringerRepresentation = false
+/*
+Print the content of context objects. By default it will be suppressed.
+
+Set PrintContextObjects = true to enable printing of the context internals.
+*/
+var PrintContextObjects = false
+var contextType = reflect.TypeOf((*context.Context)(nil)).Elem()
+
//The default indentation string emitted by the format package
var Indent = " "
@@ -57,6 +66,8 @@
Modify format.MaxDepth to control how deep the recursion is allowed to go
Set format.UseStringerRepresentation to true to return object.GoString() or object.String() when available instead of
recursing into the object.
+
+Set PrintContextObjects to true to print the content of objects implementing context.Context
*/
func Object(object interface{}, indentation uint) string {
indent := strings.Repeat(Indent, int(indentation))
@@ -124,6 +135,12 @@
}
}
+ if !PrintContextObjects {
+ if value.Type().Implements(contextType) && indentation > 1 {
+ return "<suppressed>"
+ }
+ }
+
switch value.Kind() {
case reflect.Bool:
return fmt.Sprintf("%v", value.Bool())
diff --git a/format/format_test.go b/format/format_test.go
index b27df8e..1b6f559 100644
--- a/format/format_test.go
+++ b/format/format_test.go
@@ -1,8 +1,11 @@
package format_test
import (
+ "context"
"fmt"
+ "net/http"
"strings"
+ "time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
@@ -465,4 +468,32 @@
})
})
})
+
+ Describe("Printing a context.Context field", func() {
+ req, _ := http.NewRequest("GET", "http://example.com/test", nil)
+ ctx, _ := context.WithTimeout(context.Background(), time.Second)
+ reqWithContext := req.WithContext(ctx)
+
+ It("Suppresses the content by default", func() {
+ Ω(Object(reqWithContext, 1)).Should(ContainSubstring("<suppressed>"))
+ })
+
+ It("Doesn't supress the context if it's the object being printed", func() {
+ Ω(Object(ctx, 1)).ShouldNot(MatchRegexp("^.*<suppressed>$"))
+ })
+
+ Context("PrintContextObjects is set", func() {
+ BeforeEach(func() {
+ PrintContextObjects = true
+ })
+
+ AfterEach(func() {
+ PrintContextObjects = false
+ })
+
+ It("Prints the context", func() {
+ Ω(Object(reqWithContext, 1)).ShouldNot(ContainSubstring("<suppressed>"))
+ })
+ })
+ })
})