Add json.Marshaler support to the Frame type. (#197)

* Add json.Marshaler support to the Frame type.

* Update regex for Go tip

* Escape periods in regular expression tests

* Implement encoding.TextMarshaler instead of json.Marshaler
This commit is contained in:
Jonathan Hall 2019-02-17 23:52:12 +01:00 committed by Dave Cheney
parent ffb6e22f01
commit 856c240a51
2 changed files with 61 additions and 0 deletions

51
json_test.go Normal file
View File

@ -0,0 +1,51 @@
package errors
import (
"encoding/json"
"regexp"
"testing"
)
func TestFrameMarshalText(t *testing.T) {
var tests = []struct {
Frame
want string
}{{
initpc,
`^github.com/pkg/errors\.init(\.ializers)? .+/github\.com/pkg/errors/stack_test.go:\d+$`,
}, {
0,
`^unknown$`,
}}
for i, tt := range tests {
got, err := tt.Frame.MarshalText()
if err != nil {
t.Fatal(err)
}
if !regexp.MustCompile(tt.want).Match(got) {
t.Errorf("test %d: MarshalJSON:\n got %q\n want %q", i+1, string(got), tt.want)
}
}
}
func TestFrameMarshalJSON(t *testing.T) {
var tests = []struct {
Frame
want string
}{{
initpc,
`^"github\.com/pkg/errors\.init(\.ializers)? .+/github\.com/pkg/errors/stack_test.go:\d+"$`,
}, {
0,
`^"unknown"$`,
}}
for i, tt := range tests {
got, err := json.Marshal(tt.Frame)
if err != nil {
t.Fatal(err)
}
if !regexp.MustCompile(tt.want).Match(got) {
t.Errorf("test %d: MarshalJSON:\n got %q\n want %q", i+1, string(got), tt.want)
}
}
}

View File

@ -83,6 +83,16 @@ func (f Frame) Format(s fmt.State, verb rune) {
}
}
// MarshalText formats a stacktrace Frame as a text string. The output is the
// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs.
func (f Frame) MarshalText() ([]byte, error) {
name := f.name()
if name == "unknown" {
return []byte(name), nil
}
return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil
}
// StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
type StackTrace []Frame