Add BsonDFromSlice, Add AssertDeepEqual
This commit is contained in:
20
assert.go
Normal file
20
assert.go
Normal 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)
|
||||
}
|
||||
}
|
||||
30
struct.go
30
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)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user