-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
metadata: Define MD type & impl Format method
Define the type to store a metadata unit for the error and implement its Format method with its test.
- Loading branch information
1 parent
2b1b2e8
commit 7cc76b3
Showing
2 changed files
with
78 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
package errors | ||
|
||
import "fmt" | ||
|
||
// MD is a key/value pair to add metadata to an error. | ||
type MD struct { | ||
K string | ||
V interface{} | ||
} | ||
|
||
// Format satisfies the fmt.Formatter interface. | ||
// It only prints when 'v' verb is used. | ||
func (md MD) Format(state fmt.State, verb rune) { | ||
if verb != 'v' { | ||
return | ||
} | ||
|
||
_, _ = fmt.Fprintf(state, "{%q: %+v}", md.K, md.V) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
package errors | ||
|
||
import ( | ||
"fmt" | ||
"math/rand" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestMD_Format(t *testing.T) { | ||
var tcases = []struct { | ||
desc string | ||
format string | ||
md MD | ||
expout string | ||
}{ | ||
{ | ||
desc: "'v' verb", | ||
format: "%v", | ||
md: MD{K: "a-key", V: "a-value"}, | ||
expout: "{\"a-key\": a-value}", | ||
}, | ||
{ | ||
desc: "'v' verb when value is a struct", | ||
format: "%v", | ||
md: MD{K: "a-key", V: struct{ Name string }{Name: "Ivan"}}, | ||
expout: "{\"a-key\": {Name:Ivan}}", | ||
}, | ||
{ | ||
desc: "'v' verb with '+' flag", | ||
format: "%+v", | ||
md: MD{K: "a key", V: 10.5}, | ||
expout: "{\"a key\": 10.5}", | ||
}, | ||
{ | ||
desc: "any other verb", | ||
format: func() string { | ||
var verbs = [...]string{ | ||
"t", "b", "c", "d", "o", "q", "x", "X", "U", "e", "E", "f", "F", "g", "G", "q", "p", "s", | ||
} | ||
|
||
return fmt.Sprintf("%%%s", verbs[rand.Intn(len(verbs))]) | ||
}(), | ||
md: MD{K: "some-key", V: "some-value"}, | ||
expout: "", | ||
}, | ||
} | ||
|
||
for i := range tcases { | ||
var tc = tcases[i] | ||
t.Run(tc.desc, func(t *testing.T) { | ||
t.Parallel() | ||
|
||
var out = fmt.Sprintf(tc.format, tc.md) | ||
assert.Equal(t, tc.expout, out) | ||
}) | ||
} | ||
} |