From 5ef16a7afc1f183652db5aac31678945017b7af6 Mon Sep 17 00:00:00 2001 From: Alexandre Tuleu Date: Wed, 12 Aug 2015 20:06:01 +0200 Subject: [PATCH] Adds basic unit testing --- logger_test.go | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++ narco_test.go | 36 ++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 logger_test.go create mode 100644 narco_test.go diff --git a/logger_test.go b/logger_test.go new file mode 100644 index 0000000..1d4b8db --- /dev/null +++ b/logger_test.go @@ -0,0 +1,60 @@ +package narco + +import ( + "bytes" + "fmt" + "log" + "net/http" + "net/http/httptest" + + . "gopkg.in/check.v1" +) + +type LogSuite struct { + *NarcoSuite + l *Logger + buffer bytes.Buffer +} + +var _ = Suite(&LogSuite{NarcoSuite: NewNarcoSuite()}) + +func (s *LogSuite) SetUpSuite(c *C) { + + s.l = NewLogger() + s.l.Logger = log.New(&s.buffer, "[narco] ", log.LstdFlags) + s.chain = s.chain.Append(s.l.Wrap()) + + c.Assert(s.chain, NotNil) +} + +func (s *LogSuite) SetUpTest(c *C) { + s.buffer.Reset() +} + +func (s *LogSuite) TestLogFormat(c *C) { + rec := httptest.NewRecorder() + req, err := http.NewRequest("GET", "http://"+httptest.DefaultRemoteAddr+"/", nil) + req.RemoteAddr = "foo" + c.Assert(err, IsNil, Commentf("Got error: %s", err)) + + data := map[string]http.HandlerFunc{ + `\[narco\] .* Requested GET on / from foo \(User-Agent: \\) +\[narco\] .* returned 200: OK, size: 1B in .* +`: func(rw http.ResponseWriter, req *http.Request) { + fmt.Fprintf(rw, req.URL.Path) + }, + `\[narco\] .* Requested GET on / from foo \(User-Agent: \\) +\[narco\] .* returned 404: Not Found, size: 10B in .* +`: func(rw http.ResponseWriter, req *http.Request) { + http.Error(rw, "foo error", http.StatusNotFound) + }, + } + + for matchString, fn := range data { + s.buffer.Reset() + s.ServeHTTP(rec, req, fn) + + c.Assert(s.buffer.String(), Matches, matchString) + + } +} diff --git a/narco_test.go b/narco_test.go new file mode 100644 index 0000000..19b9f52 --- /dev/null +++ b/narco_test.go @@ -0,0 +1,36 @@ +package narco + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/codemodus/chain" + "golang.org/x/net/context" + . "gopkg.in/check.v1" +) + +type NarcoSuite struct { + chain chain.Chain + ctx context.Context +} + +func Test(t *testing.T) { TestingT(t) } + +func NewNarcoSuite() *NarcoSuite { + ctx := context.Background() + return &NarcoSuite{ + ctx: ctx, + chain: chain.New(), + } +} + +func (s *NarcoSuite) ServeHTTP(rec *httptest.ResponseRecorder, req *http.Request, handlerfunc http.HandlerFunc) { + s.chain.EndFn(func(ctx context.Context, rw http.ResponseWriter, req *http.Request) { + handlerfunc.ServeHTTP(rw, req) + }).ServeHTTP(rec, req) +} + +func (s *NarcoSuite) ServeHTTPContext(rec *httptest.ResponseRecorder, req *http.Request, handlerfunc chain.HandlerFunc) { + s.chain.EndFn(handlerfunc).ServeHTTP(rec, req) +}