Skip to content

Commit

Permalink
unit tests to check the log timestamp format
Browse files Browse the repository at this point in the history
Signed-off-by: Sergey Vilgelm <sergey@vilgelm.com>
  • Loading branch information
SVilgelm committed Aug 25, 2022
1 parent d15c619 commit b5872f9
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions cmd/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@ package cmd
import (
"bytes"
"context"
"encoding/json"
"strings"
"testing"
"time"

"github.com/open-policy-agent/opa/logging"
"github.com/open-policy-agent/opa/test/e2e"
)

Expand Down Expand Up @@ -100,6 +104,74 @@ func TestInitRuntimeVerifyNonBundle(t *testing.T) {
}
}

func TestRunServerCheckLogTimestampFormat(t *testing.T) {
for _, format := range []string{time.Kitchen, time.RFC3339Nano} {
t.Run(format, func(t *testing.T) {
t.Run("parameter", func(t *testing.T) {
params := newTestRunParams()
params.logTimestampFormat = format
checkLogTimeStampFormat(t, params, format)
})
t.Run("environment variable", func(t *testing.T) {
t.Setenv("OPA_LOG_TIMESTAMP_FORMAT", format)
params := newTestRunParams()
checkLogTimeStampFormat(t, params, format)
})
})
}
}

func checkLogTimeStampFormat(t *testing.T, params runCmdParams, format string) {
ctx, cancel := context.WithCancel(context.Background())

rt, err := initRuntime(ctx, params, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
var buf bytes.Buffer
logger := rt.Manager.Logger().(*logging.StandardLogger)
logger.SetOutput(&buf)
testRuntime := e2e.WrapRuntime(ctx, cancel, rt)

done := make(chan bool)
go func() {
err := rt.Serve(ctx)
if err != nil {
t.Errorf("Unexpected error: %s", err)
}
done <- true
}()

err = testRuntime.WaitForServer()
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}

validateBasicServe(t, testRuntime)

cancel()
<-done

for _, line := range strings.Split(buf.String(), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
var rec struct {
Time string `json:"time"`
}
if err := json.Unmarshal([]byte(line), &rec); err != nil {
t.Fatalf("incorrect log message %s: %v", line, err)
}
if rec.Time == "" {
t.Fatalf("the time field is empty in log message: %s", line)
}
if _, err := time.Parse(format, rec.Time); err != nil {
t.Fatalf("incorrect timestamp format %q: %v", rec.Time, err)
}
}
}

func newTestRunParams() runCmdParams {
params := newRunParams()
params.rt.GracefulShutdownPeriod = 1
Expand Down

0 comments on commit b5872f9

Please sign in to comment.