added tests

This commit is contained in:
Roberto Bampi 2014-11-02 19:31:15 +01:00
parent 9bf47770d5
commit 4e014d4268
2 changed files with 94 additions and 1 deletions

View File

@ -1,4 +1,4 @@
package sentry_hook
package logrus_sentry
import (
"github.com/Sirupsen/logrus"

View File

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