Skip to content

Commit

Permalink
Add format.GomegaString() to allow custom formatting of objects for t…
Browse files Browse the repository at this point in the history
…ests only
  • Loading branch information
khaf committed Mar 17, 2021
1 parent c3c0920 commit 685d88b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
18 changes: 15 additions & 3 deletions format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ var Indent = " "

var longFormThreshold = 20

// GomegaStringer allows for custom formating of objects for gomega.
type GomegaStringer interface {
// GomegaString will be used to custom format an object.
// It does not follow UseStringerRepresentation value and will always be called regardless.
GomegaString() string
}

/*
Generates a formatted matcher success/failure message of the form:
Expand Down Expand Up @@ -219,9 +226,14 @@ func formatValue(value reflect.Value, indentation uint) string {
return "nil"
}

if UseStringerRepresentation {
if value.CanInterface() {
obj := value.Interface()
// GomegaStringer will take precedence to other representations and disregards UseStringerRepresentation
if value.CanInterface() {
obj := value.Interface()
if x, ok := obj.(GomegaStringer); ok {
return x.GomegaString()
}

if UseStringerRepresentation {
switch x := obj.(type) {
case fmt.GoStringer:
return x.GoString()
Expand Down
15 changes: 15 additions & 0 deletions format/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ func (g Stringer) String() string {
return "string"
}

type gomegaStringer struct {
}

func (g gomegaStringer) GomegaString() string {
return "gomegastring"
}

var _ = Describe("Format", func() {
match := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher {
if len(args) > 0 {
Expand Down Expand Up @@ -654,6 +661,14 @@ var _ = Describe("Format", func() {
Expect(Object(Stringer{}, 1)).Should(ContainSubstring("<format_test.Stringer>: string"))
})
})

When("passed a GomegaStringer", func() {
It("should use what GomegaString() returns", func() {
Expect(Object(gomegaStringer{}, 1)).Should(ContainSubstring("<format_test.gomegaStringer>: gomegastring"))
UseStringerRepresentation = false
Expect(Object(gomegaStringer{}, 1)).Should(ContainSubstring("<format_test.gomegaStringer>: gomegastring"))
})
})
})

Describe("Printing a context.Context field", func() {
Expand Down

0 comments on commit 685d88b

Please sign in to comment.