Skip to content

Commit

Permalink
test: mongodb utilities test refactor (#435)
Browse files Browse the repository at this point in the history
  • Loading branch information
fredmaggiowski authored Jan 27, 2025
1 parent d1d937a commit 52042fd
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 33 deletions.
3 changes: 1 addition & 2 deletions custom_builtins/mongoclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ func (mongoClient *MongoClient) FindOne(ctx context.Context, collectionName stri
result := collection.FindOne(ctx, query)

var bsonDocument bson.D
err := result.Decode(&bsonDocument)
if err != nil {
if err := result.Decode(&bsonDocument); err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
log.WithField("error", map[string]any{"message": err.Error()}).Warn("no document found")
return nil, nil
Expand Down
51 changes: 23 additions & 28 deletions custom_builtins/mongoclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,8 @@ package custom_builtins

import (
"context"
"fmt"
"os"
"testing"

"github.com/rond-authz/rond/internal/mongoclient"
"github.com/rond-authz/rond/internal/testutils"
"github.com/rond-authz/rond/logging"

Expand All @@ -30,13 +27,10 @@ import (
)

func TestNewMongoClient(t *testing.T) {
log := logging.NewNoOpLogger()

mongoDBURL, _ := getMongoDBURL(t)
mongoClient, err := mongoclient.NewMongoClient(log, mongoDBURL, mongoclient.ConnectionOpts{})
require.NoError(t, err)
actualClient, dbName := testutils.GetAndDisposeMongoClient(t)
mockClient := testutils.MockMongoClient{ActualClient: actualClient, DBName: dbName}

client, err := NewMongoClient(logging.NewNoOpLogger(), mongoClient)
client, err := NewMongoClient(logging.NewNoOpLogger(), mockClient)
require.NoError(t, err)
require.NotNil(t, client)
}
Expand Down Expand Up @@ -67,16 +61,15 @@ func TestGetMongoCollectionFromContext(t *testing.T) {

func TestMongoFindOne(t *testing.T) {
log := logging.NewNoOpLogger()
mongoDBURL := testutils.GetMongoDBURL(t)
client, err := mongoclient.NewMongoClient(log, mongoDBURL, mongoclient.ConnectionOpts{})
require.NoError(t, err)
defer client.Disconnect()

mongoClient, err := NewMongoClient(log, client)
client, dbName := testutils.GetAndDisposeMongoClient(t)
mockClient := testutils.MockMongoClient{ActualClient: client, DBName: dbName}

mongoClient, err := NewMongoClient(log, mockClient)
require.NoError(t, err)

collectionName := "my-collection"
populateCollection(t, client.Collection(collectionName))
populateCollection(t, mockClient.Collection(collectionName))

t.Run("finds a document", func(t *testing.T) {
result, err := mongoClient.FindOne(context.Background(), collectionName, map[string]interface{}{
Expand Down Expand Up @@ -105,6 +98,21 @@ func TestMongoFindOne(t *testing.T) {
require.NoError(t, err)
require.True(t, result == nil)
})

t.Run("fails to find one for closed connection", func(t *testing.T) {
client, dbName := testutils.GetMongoClientCallerMUSTDispose(t)
mockClient := testutils.MockMongoClient{ActualClient: client, DBName: dbName}
mongoClient, err := NewMongoClient(log, mockClient)
require.NoError(t, err)

client.Disconnect(context.Background())

result, err := mongoClient.FindOne(context.Background(), collectionName, map[string]interface{}{
"key": 42,
})
require.Error(t, err)
require.Nil(t, result)
})
}

func TestMongoFindMany(t *testing.T) {
Expand Down Expand Up @@ -195,16 +203,3 @@ func populateCollection(t *testing.T, collection *mongo.Collection) {
collection.Drop(ctx)
})
}

func getMongoDBURL(t *testing.T) (connectionString string, dbName string) {
t.Helper()
mongoHost := os.Getenv("MONGO_HOST_CI")
if mongoHost == "" {
mongoHost = testutils.LocalhostMongoDB
t.Logf("Connection to localhost MongoDB, on CI env this is a problem!")
}

dbName = testutils.GetRandomName(10)
connectionString = fmt.Sprintf("mongodb://%s/%s", mongoHost, dbName)
return
}
4 changes: 2 additions & 2 deletions internal/testutils/mongoclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ type MockMongoClient struct {
DBName string
}

func (m *MockMongoClient) Collection(collectionName string) *mongo.Collection {
func (m MockMongoClient) Collection(collectionName string) *mongo.Collection {
if m.ActualClient == nil {
return nil
}
return m.ActualClient.Database(m.DBName).Collection(collectionName)
}

func (m *MockMongoClient) Disconnect() error {
func (m MockMongoClient) Disconnect() error {
if m.ActualClient == nil {
return nil
}
Expand Down
15 changes: 14 additions & 1 deletion internal/testutils/mongodb.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,19 @@ func GetAndDisposeMongoClient(t *testing.T) (*mongo.Client, string) {
return client, dbName
}

func GetMongoClientCallerMUSTDispose(t *testing.T) (*mongo.Client, string) {
t.Helper()

mongoHost := GetMongoHost(t)
dbName := GetRandomName(10)

clientOpts := options.Client().ApplyURI(formatMongoDBURL(mongoHost, dbName))

client, err := mongo.Connect(context.Background(), clientOpts)
require.NoError(t, err, "failed mongo db connection")
return client, dbName
}

// GetAndDisposeTestCollection returns a collection from a random database.
// The function performs test clean up by dropping the database and closing MongoDB client connection.
// The returned collections are meant to be used for roles and bindings, respectively.
Expand Down Expand Up @@ -111,7 +124,7 @@ func disposeFactory(t *testing.T, client *mongo.Client, dbName string) func() {
// This sleep has been added to avoid mongo race condition
time.Sleep(100 * time.Millisecond)
if err := client.Database(dbName).Drop(context.Background()); err != nil {
t.Fatalf("drop collcetion failed %s", err.Error())
t.Fatalf("drop collection failed %s", err.Error())
}
if err := client.Disconnect(context.Background()); err != nil {
t.Fatalf("db disconnect failed %s", err.Error())
Expand Down

0 comments on commit 52042fd

Please sign in to comment.