소스 검색

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
Jonathan Hall 7 년 전
부모
커밋
856c240a51
2개의 변경된 파일61개의 추가작업 그리고 0개의 파일을 삭제
  1. 51 0
      json_test.go
  2. 10 0
      stack.go

+ 51 - 0
json_test.go

@@ -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)
+		}
+	}
+}

+ 10 - 0
stack.go

@@ -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