Skip to content
Snippets Groups Projects
Commit f42e1a6d authored by Jack Robertson's avatar Jack Robertson
Browse files

chore: add testify and improve test

parent 53bf6b94
No related branches found
Tags v1.5.5
No related merge requests found
......@@ -2,4 +2,13 @@ module gitlab.nexdev.uk/pub/go-slog
go 1.20
require golang.org/x/exp v0.0.0-20230711023510-fffb14384f22
require (
github.com/stretchr/testify v1.8.4
golang.org/x/exp v0.0.0-20230711023510-fffb14384f22
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
......@@ -4,31 +4,69 @@ import (
"bufio"
"bytes"
"encoding/json"
"github.com/stretchr/testify/assert"
"golang.org/x/exp/slog"
"testing"
"time"
)
type log struct {
Date time.Time `json:"date"`
Status string `json:"status"`
Message string `json:"message"`
Source slog.Source `json:"source"`
}
func TestNew(t *testing.T) {
// Arrange
var buf bytes.Buffer
logger := New(WithWriter(&buf))
// Act
logger.Info("Foo", slog.String("bar", "baz"))
logger.Error("Bar", slog.String("baz", "qux"))
// Assert
scanner := bufio.NewScanner(&buf)
// Scan the first log.
scanner.Scan()
infoLog := scanner.Bytes()
var infoLogMap map[string]any
if err := json.Unmarshal(infoLog, &infoLogMap); err != nil {
t.Errorf("Failed to unmarshal info log: %s", err.Error())
}
t.Log(infoLogMap)
if infoLogMap["status"] != "info" {
t.Errorf("Expected info log level, got %s", infoLogMap["level"])
// Scan the first log
assert.True(t, scanner.Scan())
var (
rawInfoLog = scanner.Bytes()
infoLog = struct {
log
Bar string `json:"bar"`
}{}
)
if err := json.Unmarshal(rawInfoLog, &infoLog); err != nil {
t.Errorf("Failed to unmarshal info log: %s", err)
}
if infoLogMap["bar"] != "baz" {
t.Errorf("Expected bar=baz, got %s", infoLogMap["bar"])
assert.Equal(t, "info", infoLog.Status)
assert.Equal(t, "Foo", infoLog.Message)
assert.Equal(t, "baz", infoLog.Bar)
assert.WithinDuration(t, time.Now(), infoLog.Date, 1*time.Second)
// Scan the second log
assert.True(t, scanner.Scan())
var (
rawErrorLog = scanner.Bytes()
errorLog = struct {
log
Baz string `json:"baz"`
}{}
)
if err := json.Unmarshal(rawErrorLog, &errorLog); err != nil {
t.Errorf("Failed to unmarshal error log: %s", err)
}
assert.Equal(t, "error", errorLog.Status)
assert.Equal(t, "Bar", errorLog.Message)
assert.Equal(t, "qux", errorLog.Baz)
assert.WithinDuration(t, time.Now(), errorLog.Date, 1*time.Second)
// Assert that there are no more logs
assert.False(t, scanner.Scan())
assert.NoError(t, scanner.Err())
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment