Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Create and Delete users functions in examples #83

Merged
merged 1 commit into from
Feb 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
163 changes: 17 additions & 146 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ rewrote it using `mongoifc`:
package users

// Original: func GetAdmins(ctx context.Context, db *mongo.Database) ([]*User, error)
func GetAdmins(ctx context.Context, db mongoifc.Database) ([]*User, error) {
var users []*User
func GetAdmins(ctx context.Context, db mongoifc.Database) ([]User, error) {
var users []User
cur, err := db.Collection(UsersCollection).Find(ctx, User{
Active: true,
IsAdmin: true,
Expand Down Expand Up @@ -118,147 +118,18 @@ and [gomock](https://github.com/golang/mock) tools.
The examples of how to use the mocks can be found in the `examples` folder or check any of the `*_test.go` files as
well.

## Example

Here you can find the examples of how to use and mock mongodb functions

```go
package main

import (
"context"
"encoding/json"
"os"

"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo/options"

"github.com/sv-tools/mongoifc"
)

const (
UsersCollection = "users"
)

type User struct {
ID string `json:"id,omitempty" bson:"_id,omitempty"`
Name string `json:"name,omitempty" bson:"name,omitempty"`
Email string `json:"email,omitempty" bson:"email,omitempty"`
Active bool `json:"active,omitempty" bson:"active,omitempty"`
IsAdmin bool `json:"is_admin,omitempty" bson:"is_admin,omitempty"`
}

func GetAdmins(ctx context.Context, db mongoifc.Database) ([]*User, error) {
var users []*User
cur, err := db.Collection(UsersCollection).Find(ctx, User{
Active: true,
IsAdmin: true,
})
if err != nil {
return nil, err
}
if err := cur.All(ctx, &users); err != nil {
return nil, err
}
return users, err
}

// go run main.go "mongodb://${MONGO_USERNAME}:${MONGO_PASSWORD}@${MONGO_HOST}:${MONGO_PORT}/?authSource=admin" "${DATABASE}"
func main() {
uri, database := os.Args[1], os.Args[2]
opt := options.Client().ApplyURI(uri)
cl, err := mongoifc.NewClient(opt)
if err != nil {
panic(err)
}

if err = cl.Connect(context.Background()); err != nil {
panic(err)
}
defer cl.Disconnect(context.Background())

db := cl.Database(database)
users, err := GetAdmins(context.Background(), db)
if err != nil {
panic(err)
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(users); err != nil {
panic(err)
}
}
```

### How to mock

```go
package main

import (
"context"
"testing"

"github.com/golang/mock/gomock"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/mongo/options"

"github.com/sv-tools/mongoifc"
gomockMocks "github.com/sv-tools/mongoifc/mocks/gomock"
mockeryMocks "github.com/sv-tools/mongoifc/mocks/mockery"
)

func TestGetAdmins(t *testing.T) {
t.Parallel()

expectedUsers := []*User{
{Name: "foo", Active: true, IsAdmin: true},
{Name: "bar", Active: true, IsAdmin: true},
}
ctx := context.Background()

t.Run("mockery", func(t *testing.T) {
t.Parallel()

cur := &mockeryMocks.Cursor{}
cur.On("All", ctx, mock.Anything).Run(func(args mock.Arguments) {
users := args[1].(*[]*User)
*users = append(*users, expectedUsers...)
}).Return(nil)

col := &mockeryMocks.Collection{}
col.On("Find", ctx, mock.AnythingOfType("User")).Return(cur, nil)

db := &mockeryMocks.Database{}
db.On("Collection", UsersCollection).Return(col)

users, err := GetAdmins(ctx, db)
require.NoError(t, err)
require.Equal(t, expectedUsers, users)
})

t.Run("gomock", func(t *testing.T) {
t.Parallel()

ctrl := gomock.NewController(t)
defer ctrl.Finish()

cur := gomockMocks.NewMockCursor(ctrl)
cur.EXPECT().All(ctx, gomock.Any()).Do(func(ctx context.Context, arg interface{}) {
users := arg.(*[]*User)
*users = append(*users, expectedUsers...)
}).Return(nil)

col := gomockMocks.NewMockCollection(ctrl)
col.EXPECT().Find(ctx, gomock.Any()).Return(cur, nil)

db := gomockMocks.NewMockDatabase(ctrl)
db.EXPECT().Collection(UsersCollection).Return(col)

users, err := GetAdmins(ctx, db)
require.NoError(t, err)
require.Equal(t, expectedUsers, users)
})
}
```
## Simple Example

to test workflow:
1. Create 4 users, with two admins, using `InsertMany` function.
2. Get the admin users only using `Find` function
3. Delete all users using `DeleteMany` function

* [users.go](https://github.com/sv-tools/mongoifc/blob/main/examples/simple/users.go) is a file with a set of functions, like:
* `Create` to create the users using `InsertMany`
* `Delete` to delete the users by given IDs
* `GetAdmins` to return the list of admin users
* [users_test.go](https://github.com/sv-tools/mongoifc/blob/main/examples/simple/users_test.go) is a file with `TestUsersWorkflow` unit tests:
* `mockery` tests the workflow using `mockery` mocks
* `gomock` tests the workflow using `gomock` mocks
* `docker` tests the workflow using real mongo database run by docker
51 changes: 43 additions & 8 deletions examples/simple/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ package simple

import (
"context"
"fmt"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"

"github.com/sv-tools/mongoifc"
)
Expand All @@ -11,17 +15,17 @@ const (
)

type User struct {
ID string `json:"id,omitempty" bson:"_id,omitempty"`
Name string `json:"name,omitempty" bson:"name,omitempty"`
Email string `json:"email,omitempty" bson:"email,omitempty"`
Active bool `json:"active,omitempty" bson:"active,omitempty"`
IsAdmin bool `json:"is_admin,omitempty" bson:"is_admin,omitempty"`
ID string `json:"id,omitempty" bson:"_id,omitempty"`
Name string `json:"name,omitempty" bson:"name,omitempty"`
Email string `json:"email,omitempty" bson:"email,omitempty"`
Active bool `json:"active,omitempty" bson:"active,omitempty"`
IsAdmin bool `json:"is_admin,omitempty" bson:"is_admin,omitempty"`
}

func GetAdmins(ctx context.Context, db mongoifc.Database) ([]*User, error) {
var users []*User
func GetAdmins(ctx context.Context, db mongoifc.Database) ([]User, error) {
var users []User
cur, err := db.Collection(UsersCollection).Find(ctx, User{
Active: true,
Active: true,
IsAdmin: true,
})
if err != nil {
Expand All @@ -32,3 +36,34 @@ func GetAdmins(ctx context.Context, db mongoifc.Database) ([]*User, error) {
}
return users, err
}

func Create(ctx context.Context, db mongoifc.Database, users ...User) ([]string, error) {
documents := make([]interface{}, len(users))
for i := 0; i < len(users); i++ {
documents[i] = users[i]
}
res, err := db.Collection(UsersCollection).InsertMany(ctx, documents)
if err != nil {
return nil, err
}
ids := make([]string, len(res.InsertedIDs))
for i := 0; i < len(res.InsertedIDs); i++ {
ids[i] = res.InsertedIDs[i].(primitive.ObjectID).Hex()
}
return ids, nil
}

func Delete(ctx context.Context, db mongoifc.Database, ids ...string) error {
documents := make([]primitive.ObjectID, len(ids))
for i := 0; i < len(ids); i++ {
id, err := primitive.ObjectIDFromHex(ids[i])
if err != nil {
return fmt.Errorf("%s: %w", ids[i], err)
}
documents[i] = id
}

filter := bson.M{"_id": bson.M{"$in": documents}}
_, err := db.Collection(UsersCollection).DeleteMany(ctx, filter)
return err
}
98 changes: 70 additions & 28 deletions examples/simple/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"

"github.com/sv-tools/mongoifc"
Expand All @@ -18,13 +20,15 @@ import (
mockeryMocks "github.com/sv-tools/mongoifc/mocks/mockery"
)

func TestGetAdmins(t *testing.T) {
t.Parallel()

expectedUsers := []*simple.User{
var (
expectedUsers = []simple.User{
{Name: "foo", Active: true, IsAdmin: true},
{Name: "bar", Active: true, IsAdmin: true},
}
)

func TestUsersWorkflow(t *testing.T) {
t.Parallel()
ctx := context.Background()

t.Run("mockery", func(t *testing.T) {
Expand All @@ -33,21 +37,36 @@ func TestGetAdmins(t *testing.T) {
cur := &mockeryMocks.Cursor{}
defer cur.AssertExpectations(t)
cur.On("All", ctx, mock.Anything).Run(func(args mock.Arguments) {
users := args[1].(*[]*simple.User)
users := args[1].(*[]simple.User)
*users = append(*users, expectedUsers...)
}).Return(nil)

col := &mockeryMocks.Collection{}
defer col.AssertExpectations(t)
col.On("InsertMany", ctx, mock.Anything).Return(
&mongo.InsertManyResult{
InsertedIDs: []interface{}{
primitive.NewObjectID(),
primitive.NewObjectID(),
primitive.NewObjectID(),
primitive.NewObjectID(),
},
},
nil,
)
col.On("Find", ctx, mock.AnythingOfType("User")).Return(cur, nil)
col.On("DeleteMany", ctx, mock.AnythingOfType("primitive.M")).Return(
&mongo.DeleteResult{
DeletedCount: 4,
},
nil,
)

db := &mockeryMocks.Database{}
defer db.AssertExpectations(t)
db.On("Collection", simple.UsersCollection).Return(col)

users, err := simple.GetAdmins(ctx, db)
require.NoError(t, err)
require.Equal(t, expectedUsers, users)
workflow(t, db)
})

t.Run("gomock", func(t *testing.T) {
Expand All @@ -58,19 +77,34 @@ func TestGetAdmins(t *testing.T) {

cur := gomockMocks.NewMockCursor(ctrl)
cur.EXPECT().All(ctx, gomock.Any()).Do(func(ctx context.Context, arg interface{}) {
users := arg.(*[]*simple.User)
users := arg.(*[]simple.User)
*users = append(*users, expectedUsers...)
}).Return(nil)

col := gomockMocks.NewMockCollection(ctrl)
col.EXPECT().InsertMany(ctx, gomock.Any()).Return(
&mongo.InsertManyResult{
InsertedIDs: []interface{}{
primitive.NewObjectID(),
primitive.NewObjectID(),
primitive.NewObjectID(),
primitive.NewObjectID(),
},
},
nil,
)
col.EXPECT().Find(ctx, gomock.Any()).Return(cur, nil)
col.EXPECT().DeleteMany(ctx, gomock.Any()).Return(
&mongo.DeleteResult{
DeletedCount: 4,
},
nil,
)

db := gomockMocks.NewMockDatabase(ctrl)
db.EXPECT().Collection(simple.UsersCollection).Return(col)
db.EXPECT().Collection(simple.UsersCollection).Return(col).AnyTimes()

users, err := simple.GetAdmins(ctx, db)
require.NoError(t, err)
require.Equal(t, expectedUsers, users)
workflow(t, db)
})

t.Run("docker", func(t *testing.T) {
Expand All @@ -91,20 +125,28 @@ func TestGetAdmins(t *testing.T) {
})

db := cl.Database(fmt.Sprintf("simple_%d", time.Now().Unix()))
res, err := db.Collection(simple.UsersCollection).InsertMany(ctx, []interface{}{
&simple.User{Name: "blocked admin", Active: false, IsAdmin: true},
&simple.User{Name: "active non-admin", Active: true, IsAdmin: false},
expectedUsers[0],
expectedUsers[1],
})
require.NoError(t, err)
require.Len(t, res.InsertedIDs, 4)

users, err := simple.GetAdmins(ctx, db)
require.NoError(t, err)
for _, u := range users {
u.ID = ""
}
require.Equal(t, expectedUsers, users)
workflow(t, db)
})
}

func workflow(t testing.TB, db mongoifc.Database) {
ctx := context.Background()
ids, err := simple.Create(ctx, db,
simple.User{Name: "blocked admin", Active: false, IsAdmin: true},
simple.User{Name: "active non-admin", Active: true, IsAdmin: false},
expectedUsers[0],
expectedUsers[1],
)
require.NoError(t, err)
require.Len(t, ids, 4)

users, err := simple.GetAdmins(ctx, db)
require.NoError(t, err)
for i, u := range users {
u.ID = ""
users[i] = u
}
require.Equal(t, expectedUsers, users)

require.NoError(t, simple.Delete(ctx, db, ids...))
}