Skip to content

Commit

Permalink
metadata: Define MD type & impl Format method
Browse files Browse the repository at this point in the history
Define the type to store a metadata unit for the error and implement
its Format method with its test.
  • Loading branch information
ifraixedes committed Dec 21, 2018
1 parent 2b1b2e8 commit 7cc76b3
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
19 changes: 19 additions & 0 deletions metadata.go
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)
}
59 changes: 59 additions & 0 deletions metadata_test.go
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)
})
}
}

0 comments on commit 7cc76b3

Please sign in to comment.