open-vault/audit/format_json_test.go

68 lines
1.7 KiB
Go
Raw Normal View History

2015-04-13 21:12:03 +00:00
package audit
import (
"bytes"
2015-08-05 14:44:48 +00:00
"strings"
2015-04-13 21:12:03 +00:00
"testing"
2015-08-05 14:44:48 +00:00
"encoding/json"
2015-04-13 21:12:03 +00:00
"github.com/hashicorp/vault/logical"
2015-06-19 03:14:20 +00:00
"errors"
2015-04-13 21:12:03 +00:00
)
func TestFormatJSON_formatRequest(t *testing.T) {
cases := map[string]struct {
Auth *logical.Auth
Req *logical.Request
2015-06-19 03:14:20 +00:00
Err error
2015-04-13 21:12:03 +00:00
Result string
}{
"auth, request": {
&logical.Auth{ClientToken: "foo", Policies: []string{"root"}},
&logical.Request{
2016-01-07 15:30:47 +00:00
Operation: logical.UpdateOperation,
2015-04-13 21:12:03 +00:00
Path: "/foo",
2015-06-19 03:14:20 +00:00
Connection: &logical.Connection{
RemoteAddr: "127.0.0.1",
},
2015-04-13 21:12:03 +00:00
},
2015-06-19 03:14:20 +00:00
errors.New("this is an error"),
2015-04-13 21:12:03 +00:00
testFormatJSONReqBasicStr,
},
}
for name, tc := range cases {
var buf bytes.Buffer
var format FormatJSON
2015-06-19 03:14:20 +00:00
if err := format.FormatRequest(&buf, tc.Auth, tc.Req, tc.Err); err != nil {
2015-04-13 21:12:03 +00:00
t.Fatalf("bad: %s\nerr: %s", name, err)
}
2015-08-05 14:44:48 +00:00
var expectedjson = new(JSONRequestEntry)
if err := json.Unmarshal([]byte(tc.Result), &expectedjson); err != nil {
t.Fatalf("bad json: %s", err)
}
var actualjson = new(JSONRequestEntry)
if err := json.Unmarshal([]byte(buf.String()), &actualjson); err != nil {
t.Fatalf("bad json: %s", err)
}
expectedjson.Time = actualjson.Time
expectedBytes, err := json.Marshal(expectedjson)
if err != nil {
t.Fatalf("unable to marshal json: %s", err)
}
if strings.TrimSpace(buf.String()) != string(expectedBytes) {
2015-04-13 21:12:03 +00:00
t.Fatalf(
2015-08-05 14:44:48 +00:00
"bad: %s\nResult:\n\n'%s'\n\nExpected:\n\n'%s'",
name, buf.String(), string(expectedBytes))
2015-04-13 21:12:03 +00:00
}
}
}
2015-08-05 14:44:48 +00:00
const testFormatJSONReqBasicStr = `{"time":"2015-08-05T13:45:46Z","type":"request","auth":{"display_name":"","policies":["root"],"metadata":null},"request":{"operation":"write","path":"/foo","data":null,"remote_address":"127.0.0.1"},"error":"this is an error"}
2015-04-13 21:12:03 +00:00
`