From 4e014d4268d34b3c861a227e6ad966512ac47883 Mon Sep 17 00:00:00 2001 From: Roberto Bampi Date: Sun, 2 Nov 2014 19:31:15 +0100 Subject: [PATCH] added tests --- hooks/sentry/sentry.go | 2 +- hooks/sentry/sentry_test.go | 93 +++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 hooks/sentry/sentry_test.go diff --git a/hooks/sentry/sentry.go b/hooks/sentry/sentry.go index 5c07eb2..74e8bbe 100644 --- a/hooks/sentry/sentry.go +++ b/hooks/sentry/sentry.go @@ -1,4 +1,4 @@ -package sentry_hook +package logrus_sentry import ( "github.com/Sirupsen/logrus" diff --git a/hooks/sentry/sentry_test.go b/hooks/sentry/sentry_test.go new file mode 100644 index 0000000..747d75f --- /dev/null +++ b/hooks/sentry/sentry_test.go @@ -0,0 +1,93 @@ +package logrus_sentry + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Sirupsen/logrus" + "github.com/getsentry/raven-go" +) + +const ( + message = "error message" + server_name = "testserver.internal" + logger_name = "test.logger" +) + +func getTestLogger() *logrus.Logger { + l := logrus.New() + l.Out = ioutil.Discard + return l +} + +func getTestDSN(t *testing.T) (string, <-chan *raven.Packet, func()) { + pch := make(chan *raven.Packet, 1) + s := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + defer req.Body.Close() + d := json.NewDecoder(req.Body) + p := &raven.Packet{} + err := d.Decode(p) + if err != nil { + t.Fatal(err.Error()) + } + + pch <- p + })) + + fragments := strings.SplitN(s.URL, "://", 2) + dsn := "%s://public:secret@%s/sentry/project-id" + + return fmt.Sprintf(dsn, fragments[0], fragments[1]), pch, s.Close +} + +func TestSpecialFields(t *testing.T) { + logger := getTestLogger() + dsn, pch, closeFn := getTestDSN(t) + defer closeFn() + + hook, err := NewSentryHook(dsn, []logrus.Level{ + logrus.ErrorLevel, + }) + + if err != nil { + t.Fatal(err.Error()) + } + logger.Hooks.Add(hook) + logger.WithFields(logrus.Fields{ + "server_name": server_name, + "logger": logger_name, + }).Error(message) + + packet := <-pch + if packet.Logger != logger_name { + t.Errorf("logger should have been %s, was %s", logger_name, packet.Logger) + } + + if packet.ServerName != server_name { + t.Errorf("server_name should have been %s, was %s", server_name, packet.ServerName) + } +} + +func TestSentryHandler(t *testing.T) { + logger := getTestLogger() + dsn, pch, closeFn := getTestDSN(t) + defer closeFn() + hook, err := NewSentryHook(dsn, []logrus.Level{ + logrus.ErrorLevel, + }) + if err != nil { + t.Fatal(err.Error()) + } + logger.Hooks.Add(hook) + + logger.Error(message) + packet := <-pch + if packet.Message != message { + t.Errorf("message should have been %s, was %s", message, packet.Message) + } +}