From 891fd10ef6fba42622f143f9e8090df4f8bf5fee Mon Sep 17 00:00:00 2001 From: tidwall Date: Sat, 24 Sep 2022 13:57:03 -0700 Subject: [PATCH] Added bson tests --- internal/server/bson.go | 17 +++++----------- internal/server/bson_test.go | 10 ++++++++++ internal/server/must.go | 16 +++++++++++++++ internal/server/must_test.go | 38 ++++++++++++++++++++++++++++++++++++ 4 files changed, 69 insertions(+), 12 deletions(-) create mode 100644 internal/server/bson_test.go create mode 100644 internal/server/must.go create mode 100644 internal/server/must_test.go diff --git a/internal/server/bson.go b/internal/server/bson.go index bcc9d2ea..c65adcbb 100644 --- a/internal/server/bson.go +++ b/internal/server/bson.go @@ -5,7 +5,6 @@ import ( "crypto/rand" "encoding/binary" "encoding/hex" - "io" "os" "sync/atomic" "time" @@ -23,23 +22,17 @@ func bsonID() string { var ( bsonProcess = uint16(os.Getpid()) bsonMachine = func() []byte { - host, err := os.Hostname() - if err != nil { - b := make([]byte, 3) - if _, err := io.ReadFull(rand.Reader, b); err != nil { - panic("random error: " + err.Error()) - } - return b - } + host, _ := os.Hostname() + b := make([]byte, 3) + Must(rand.Read(b)) + host = Default(host, string(b)) hw := md5.New() hw.Write([]byte(host)) return hw.Sum(nil)[:3] }() bsonCounter = func() uint32 { b := make([]byte, 4) - if _, err := io.ReadFull(rand.Reader, b); err != nil { - panic("random error: " + err.Error()) - } + Must(rand.Read(b)) return binary.BigEndian.Uint32(b) }() ) diff --git a/internal/server/bson_test.go b/internal/server/bson_test.go new file mode 100644 index 00000000..ca157446 --- /dev/null +++ b/internal/server/bson_test.go @@ -0,0 +1,10 @@ +package server + +import "testing" + +func TestBSON(t *testing.T) { + id := bsonID() + if len(id) != 24 { + t.Fail() + } +} diff --git a/internal/server/must.go b/internal/server/must.go new file mode 100644 index 00000000..b50ba653 --- /dev/null +++ b/internal/server/must.go @@ -0,0 +1,16 @@ +package server + +func Must[T any](a T, err error) T { + if err != nil { + panic(err) + } + return a +} + +func Default[T comparable](a, b T) T { + var c T + if a == c { + return b + } + return a +} diff --git a/internal/server/must_test.go b/internal/server/must_test.go new file mode 100644 index 00000000..de3bcade --- /dev/null +++ b/internal/server/must_test.go @@ -0,0 +1,38 @@ +package server + +import ( + "errors" + "testing" +) + +func TestMust(t *testing.T) { + if Must(1, nil) != 1 { + t.Fail() + } + func() { + var ended bool + defer func() { + if ended { + t.Fail() + } + err, ok := recover().(error) + if !ok { + t.Fail() + } + if err.Error() != "ok" { + t.Fail() + } + }() + Must(1, errors.New("ok")) + ended = true + }() +} + +func TestDefault(t *testing.T) { + if Default("", "2") != "2" { + t.Fail() + } + if Default("1", "2") != "1" { + t.Fail() + } +}