Split Collectin's add method to add and create methods.
[arvados.git] / sdk / go / httpserver / logger_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package httpserver
6
7 import (
8         "bytes"
9         "encoding/json"
10         "net/http"
11         "net/http/httptest"
12         "os"
13         "testing"
14         "time"
15
16         log "github.com/Sirupsen/logrus"
17         check "gopkg.in/check.v1"
18 )
19
20 func Test(t *testing.T) {
21         check.TestingT(t)
22 }
23
24 var _ = check.Suite(&Suite{})
25
26 type Suite struct{}
27
28 func (s *Suite) TestLogRequests(c *check.C) {
29         defer log.SetOutput(os.Stdout)
30         captured := &bytes.Buffer{}
31         log.SetOutput(captured)
32         log.SetFormatter(&log.JSONFormatter{
33                 TimestampFormat: time.RFC3339Nano,
34         })
35         h := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
36                 w.Write([]byte("hello world"))
37         })
38         req, err := http.NewRequest("GET", "https://foo.example/bar", nil)
39         req.Header.Set("X-Forwarded-For", "1.2.3.4:12345")
40         c.Assert(err, check.IsNil)
41         resp := httptest.NewRecorder()
42         AddRequestIDs(LogRequests(h)).ServeHTTP(resp, req)
43
44         dec := json.NewDecoder(captured)
45
46         gotReq := make(map[string]interface{})
47         err = dec.Decode(&gotReq)
48         c.Logf("%#v", gotReq)
49         c.Check(gotReq["RequestID"], check.Matches, "req-[a-z0-9]{20}")
50         c.Check(gotReq["reqForwardedFor"], check.Equals, "1.2.3.4:12345")
51         c.Check(gotReq["msg"], check.Equals, "request")
52
53         gotResp := make(map[string]interface{})
54         err = dec.Decode(&gotResp)
55         c.Logf("%#v", gotResp)
56         c.Check(gotResp["RequestID"], check.Equals, gotReq["RequestID"])
57         c.Check(gotResp["reqForwardedFor"], check.Equals, "1.2.3.4:12345")
58         c.Check(gotResp["msg"], check.Equals, "response")
59
60         c.Assert(gotResp["time"], check.FitsTypeOf, "")
61         _, err = time.Parse(time.RFC3339Nano, gotResp["time"].(string))
62         c.Check(err, check.IsNil)
63
64         for _, key := range []string{"timeToStatus", "timeWriteBody", "timeTotal"} {
65                 c.Assert(gotResp[key], check.FitsTypeOf, float64(0))
66                 c.Check(gotResp[key].(float64), check.Not(check.Equals), float64(0))
67         }
68 }