Skip to content

Commit

Permalink
Add unit test for stats logging in forwarder.
Browse files Browse the repository at this point in the history
  • Loading branch information
s-l-teichmann committed Sep 27, 2023
1 parent 2807905 commit 3ab78f8
Showing 1 changed file with 59 additions and 1 deletion.
60 changes: 59 additions & 1 deletion cmd/csaf_downloader/forwarder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@

package main

import "testing"
import (
"bufio"
"bytes"
"encoding/json"
"log/slog"
"testing"
)

func TestValidationStatusUpdate(t *testing.T) {
sv := validValidationStatus
Expand All @@ -24,3 +30,55 @@ func TestValidationStatusUpdate(t *testing.T) {
t.Fatalf("got %q expected %q", sv, notValidatedValidationStatus)
}
}

func TestForwarderLogStats(t *testing.T) {
orig := slog.Default()
defer slog.SetDefault(orig)

var buf bytes.Buffer
h := slog.NewJSONHandler(&buf, &slog.HandlerOptions{
Level: slog.LevelInfo,
})
lg := slog.New(h)
slog.SetDefault(lg)

cfg := &config{}
fw := newForwarder(cfg)
fw.failed = 11
fw.succeeded = 13

done := make(chan struct{})
go func() {
defer close(done)
fw.run()
}()
fw.log()
fw.close()
<-done

type fwStats struct {
Msg string `json:"msg"`
Succeeded int `json:"succeeded"`
Failed int `json:"failed"`
}
sc := bufio.NewScanner(bytes.NewReader(buf.Bytes()))
found := false
for sc.Scan() {
var fws fwStats
if err := json.Unmarshal(sc.Bytes(), &fws); err != nil {
t.Fatalf("JSON parsing log failed: %v", err)
}
if fws.Msg == "Forward statistics" &&
fws.Failed == 11 &&
fws.Succeeded == 13 {
found = true
break
}
}
if err := sc.Err(); err != nil {
t.Fatalf("scanning log failed: %v", err)
}
if !found {
t.Fatal("Cannot find forward statistics in log")
}
}

0 comments on commit 3ab78f8

Please sign in to comment.