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" "crypto/rand"
"encoding/binary" "encoding/binary"
"encoding/hex" "encoding/hex"
"io"
"os" "os"
"sync/atomic" "sync/atomic"
"time" "time"
@ -23,23 +22,17 @@ func bsonID() string {
var ( var (
bsonProcess = uint16(os.Getpid()) bsonProcess = uint16(os.Getpid())
bsonMachine = func() []byte { bsonMachine = func() []byte {
host, err := os.Hostname() host, _ := os.Hostname()
if err != nil { b := make([]byte, 3)
b := make([]byte, 3) Must(rand.Read(b))
if _, err := io.ReadFull(rand.Reader, b); err != nil { host = Default(host, string(b))
panic("random error: " + err.Error())
}
return b
}
hw := md5.New() hw := md5.New()
hw.Write([]byte(host)) hw.Write([]byte(host))
return hw.Sum(nil)[:3] return hw.Sum(nil)[:3]
}() }()
bsonCounter = func() uint32 { bsonCounter = func() uint32 {
b := make([]byte, 4) b := make([]byte, 4)
if _, err := io.ReadFull(rand.Reader, b); err != nil { Must(rand.Read(b))
panic("random error: " + err.Error())
}
return binary.BigEndian.Uint32(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()
}
}