Added bson tests

This commit is contained in:
tidwall 2022-09-24 13:57:03 -07:00
parent d8ecbba0be
commit 891fd10ef6
4 changed files with 69 additions and 12 deletions

View File

@ -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 {
host, _ := os.Hostname()
b := make([]byte, 3)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
panic("random error: " + err.Error())
}
return b
}
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)
}()
)

View File

@ -0,0 +1,10 @@
package server
import "testing"
func TestBSON(t *testing.T) {
id := bsonID()
if len(id) != 24 {
t.Fail()
}
}

16
internal/server/must.go Normal file
View File

@ -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
}

View File

@ -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()
}
}