80 lines
1.7 KiB
Go
80 lines
1.7 KiB
Go
package mongoext
|
|
|
|
import (
|
|
"bytes"
|
|
"testing"
|
|
|
|
"git.blackforestbytes.com/BlackForestBytes/goext/tst"
|
|
"go.mongodb.org/mongo-driver/v2/bson"
|
|
)
|
|
|
|
func TestCreateGoExtBsonRegistryNotNil(t *testing.T) {
|
|
reg := CreateGoExtBsonRegistry()
|
|
if reg == nil {
|
|
t.Fatal("registry should not be nil")
|
|
}
|
|
}
|
|
|
|
func TestCreateGoExtBsonRegistryEmbeddedDocumentDecodesAsBsonM(t *testing.T) {
|
|
reg := CreateGoExtBsonRegistry()
|
|
|
|
doc := bson.M{
|
|
"name": "alice",
|
|
"nested": bson.M{
|
|
"key": "value",
|
|
"num": int32(42),
|
|
},
|
|
}
|
|
|
|
raw, err := bson.Marshal(doc)
|
|
tst.AssertNoErr(t, err)
|
|
|
|
dec := bson.NewDecoder(bson.NewDocumentReader(bytes.NewReader(raw)))
|
|
dec.SetRegistry(reg)
|
|
|
|
var decoded map[string]any
|
|
err = dec.Decode(&decoded)
|
|
tst.AssertNoErr(t, err)
|
|
|
|
nested, ok := decoded["nested"].(bson.M)
|
|
if !ok {
|
|
t.Fatalf("expected nested to be bson.M, got %T", decoded["nested"])
|
|
}
|
|
|
|
tst.AssertEqual(t, nested["key"].(string), "value")
|
|
}
|
|
|
|
func TestCreateGoExtBsonRegistryStructFieldOfTypeAny(t *testing.T) {
|
|
reg := CreateGoExtBsonRegistry()
|
|
|
|
type wrapper struct {
|
|
Payload any `bson:"payload"`
|
|
}
|
|
|
|
source := wrapper{Payload: bson.M{"x": "y"}}
|
|
raw, err := bson.Marshal(source)
|
|
tst.AssertNoErr(t, err)
|
|
|
|
dec := bson.NewDecoder(bson.NewDocumentReader(bytes.NewReader(raw)))
|
|
dec.SetRegistry(reg)
|
|
|
|
var decoded wrapper
|
|
err = dec.Decode(&decoded)
|
|
tst.AssertNoErr(t, err)
|
|
|
|
payload, ok := decoded.Payload.(bson.M)
|
|
if !ok {
|
|
t.Fatalf("expected Payload to be bson.M, got %T", decoded.Payload)
|
|
}
|
|
tst.AssertEqual(t, payload["x"].(string), "y")
|
|
}
|
|
|
|
func TestCreateGoExtBsonRegistryReturnsIndependentInstances(t *testing.T) {
|
|
r1 := CreateGoExtBsonRegistry()
|
|
r2 := CreateGoExtBsonRegistry()
|
|
|
|
if r1 == r2 {
|
|
t.Error("expected each call to return a new registry instance")
|
|
}
|
|
}
|