Move audit subscribe to client, Fix tests
This commit is contained in:
@@ -2,6 +2,7 @@ package mongo
|
||||
|
||||
import (
|
||||
"os"
|
||||
"fmt"
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -235,4 +236,72 @@ func TestInsertOne_Discriminate_EnsureStore(t *testing.T) {
|
||||
if saved["store"] != "str_1234" {
|
||||
t.Fatal("Wrong store")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertOne_WithAudit(t *testing.T) {
|
||||
client := GetMongoClient()
|
||||
|
||||
var (
|
||||
onAudit_calls int
|
||||
onAudit_after any
|
||||
onAudit_context any
|
||||
)
|
||||
|
||||
cancel := client.Subscribe(func(audit *AuditResult) error {
|
||||
onAudit_calls++
|
||||
onAudit_after = audit.After
|
||||
onAudit_context = audit.Context
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
data := map[string]any {
|
||||
"_id": "su_123458",
|
||||
"name": "MyNameTODelete",
|
||||
"age": int32(25),
|
||||
}
|
||||
|
||||
o, err := client.InsertOne(context.Background(), "mydb", "mycollection", data)
|
||||
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||
|
||||
cancel()
|
||||
|
||||
ctx := context.Background()
|
||||
ctx = context.WithValue(ctx, "account", "xxxxxx")
|
||||
ctx = context.WithValue(ctx, "store", "str_4321")
|
||||
err = client.DeleteOne(ctx, "mydb", "mycollection", bson.M{"_id": o["_id"].(string)})
|
||||
if err != nil { t.Fatalf("Failed to deleteOne %#v", err) }
|
||||
|
||||
// raw query
|
||||
var results bson.M
|
||||
filter := bson.M{ "name": "MyNameTODelete" }
|
||||
|
||||
c := client.Client.Database("mydb").Collection("mycollection")
|
||||
c.FindOne(context.Background(), filter).Decode(&results)
|
||||
|
||||
if results != nil {
|
||||
t.Fatalf("Should have no results not %v", results)
|
||||
}
|
||||
|
||||
if onAudit_calls != 1 {
|
||||
t.Fatalf("ondelete should have been called once, not %d", onAudit_calls)
|
||||
}
|
||||
|
||||
if onAudit_after != nil {
|
||||
tp := fmt.Sprintf("%T", onAudit_after)
|
||||
|
||||
expectedType := fmt.Sprintf("%T", map[string]any{})
|
||||
if tp != expectedType {
|
||||
t.Fatalf("after has the wrong type %s", tp)
|
||||
}
|
||||
|
||||
after := onAudit_after.(map[string]any)
|
||||
|
||||
AssertSubset(t, after, o, "Should have been equal")
|
||||
}
|
||||
|
||||
if onAudit_context != nil {
|
||||
ctx := onAudit_context.(map[string]any)
|
||||
AssertSubset(t, ctx, map[string]any{"account": "xxxxxx", "store": "str_4321"}, "Should have been equal")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user