Add BsonDFromSlice, Add AssertDeepEqual

This commit is contained in:
George Suntres
2026-04-25 10:11:40 -04:00
parent 28dcfb9e4c
commit 13c75f62b1
3 changed files with 66 additions and 2 deletions

20
assert.go Normal file
View File

@@ -0,0 +1,20 @@
package commons
import (
"testing"
"bytes"
"go.mongodb.org/mongo-driver/v2/bson"
)
// AssertDeepEqual compares equality by comparing bytes.
func AssertDeepEqual(t *testing.T, expected, actual any) {
t.Helper()
expJSON, _ := bson.MarshalExtJSON(expected, true, true)
actJSON, _ := bson.MarshalExtJSON(actual, true, true)
if !bytes.Equal(expJSON, actJSON) {
t.Fatalf("expected %s, got %s", expJSON, actJSON)
}
}

View File

@@ -212,6 +212,32 @@ func deepCopy(v any) any {
}
}
func BsonDFromSlice(in [][]any) bson.D {
if in == nil {
return bson.D{}
}
var doc bson.D
for _, pair := range in {
if len(pair) != 2 {
continue
}
key, ok := pair[0].(string)
if !ok {
continue // or error
}
doc = append(doc, bson.E{
Key: key,
Value: pair[1], // already `any`
})
}
return doc
}
func BsonDGetAny(d bson.D, key string) (any, bool) {
for _, e := range d {
if e.Key == key {
@@ -263,14 +289,14 @@ func BsonToStruct(m bson.M, o any) error {
// MapToStruct will convert a map[string]any to a struct.
func MapToStruct(m map[string]any, o any) error {
b, err := bson.Marshal(m)
b, err := json.Marshal(m)
if err != nil {
log.Printf("Failed marshal %v", err)
return err
}
err = bson.Unmarshal(b, o)
err = json.Unmarshal(b, o)
if err != nil {
log.Printf("Failed to unmarshal %v", err)

View File

@@ -3,8 +3,26 @@ package commons
import (
"fmt"
"testing"
"go.mongodb.org/mongo-driver/v2/bson"
)
func TestBsonDFromSlice(t *testing.T) {
in := [][]any{
{"first", -1},
{"second", 1},
}
d := BsonDFromSlice(in)
expected := bson.D{
{Key: "first", Value: -1},
{Key: "second", Value: 1},
}
AssertDeepEqual(t, d, expected)
}
func TestStructHasProperty(t *testing.T) {
type O struct {
Name string