diff --git a/assert.go b/assert.go new file mode 100644 index 0000000..608e142 --- /dev/null +++ b/assert.go @@ -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) + } +} diff --git a/struct.go b/struct.go index b6609da..30054d0 100644 --- a/struct.go +++ b/struct.go @@ -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) diff --git a/struct_test.go b/struct_test.go index 291ed51..bb8c2b1 100644 --- a/struct_test.go +++ b/struct_test.go @@ -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