@@ -21,9 +21,7 @@ package audit
2121import (
2222 "bytes"
2323 "encoding/json"
24- "io"
2524 "log"
26- "os"
2725 "testing"
2826 "time"
2927)
@@ -36,45 +34,37 @@ var (
3634)
3735
3836func TestStdOutLogger_Log (t * testing.T ) {
39- orig := os . Stdout
40- r , w , _ := os . Pipe ( )
41- os . Stdout = w
37+ var buf bytes. Buffer
38+ log . SetOutput ( & buf )
39+ log . SetFlags ( 0 )
4240
4341 event := & Event {PolicyName : "test policy" , Principal : "test principal" }
4442 auditLogger .Log (event )
4543
46- w .Close ()
44+ expected := `{"fullMethodName":"","principal":"test principal","policyName":"test policy","matchedRule":"","authorized":false`
45+ if buf .String () != (expected + ",\" timestamp\" :\" " + time .Now ().Format (time .RFC3339 ) + "\" }\n " ) {
46+ t .Fatalf ("unexpected error\n want:%v\n got:%v" , expected , buf .String ())
47+ }
48+ }
49+
50+ func TestStdOutLogger_LogAllEventFields (t * testing.T ) {
4751 var buf bytes.Buffer
48- _ , err := io .Copy (& buf , r )
49- if err != nil {
50- log .Fatal (err )
52+ log .SetOutput (& buf )
53+ log .SetFlags (0 )
54+
55+ event := & Event {
56+ FullMethodName : "/helloworld.Greeter/SayHello" ,
57+ Principal : "spiffe://example.org/ns/default/sa/default/backend" ,
58+ PolicyName : "example-policy" ,
59+ MatchedRule : "dev-access" ,
60+ Authorized : true ,
5161 }
62+ auditLogger .Log (event )
5263
53- expected := `{"fullMethodName":"","principal":"test principal","policyName":"test policy","matchedRule":"","authorized":false`
64+ expected := `{"fullMethodName":"/helloworld.Greeter/SayHello",` +
65+ `"principal":"spiffe://example.org/ns/default/sa/default/backend","policyName":"example-policy",` +
66+ `"matchedRule":"dev-access","authorized":true`
5467 if buf .String () != (expected + ",\" timestamp\" :\" " + time .Now ().Format (time .RFC3339 ) + "\" }\n " ) {
5568 t .Fatalf ("unexpected error\n want:%v\n got:%v" , expected , buf .String ())
5669 }
57- os .Stdout = orig
5870}
59-
60- //func TestStdOutLogger_LogFullMethodName(t *testing.T) {
61- // orig := os.Stdout
62- // r, w, _ := os.Pipe()
63- // os.Stdout = w
64- //
65- // event := &Event{PolicyName: "test policy", Principal: "test principal", FullMethodName: "/helloworld.Greeter/SayHello"}
66- // auditLogger.Log(event)
67- //
68- // w.Close()
69- // var buf bytes.Buffer
70- // _, err := io.Copy(&buf, r)
71- // if err != nil {
72- // log.Fatal(err)
73- // }
74- //
75- // expected := `{"fullMethodName":"","principal":"test principal","policyName":"test policy","matchedRule":"","authorized":false`
76- // if buf.String() != (expected + ",\"timestamp\":\"" + time.Now().Format(time.RFC3339) + "\"}\n") {
77- // t.Fatalf("unexpected error\nwant:%v\n got:%v", expected, buf.String())
78- // }
79- // os.Stdout = orig
80- //}
0 commit comments