Skip to content

Commit

Permalink
Minor tests refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
dmitrymomot committed Jan 20, 2024
1 parent 2583fac commit 6259ff0
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 5 deletions.
4 changes: 2 additions & 2 deletions Makefile
@@ -1,8 +1,8 @@
.PHONY: test
test:
@echo "Starting MongoDB..."
docker-compose -f ./tests/docker-compose.yml up -d
docker-compose -f ./docker-compose.yml up -d
@echo "Running tests..."
MONGODB_URI="mongodb://username:password@localhost:27017" go test -v -p 1 -count=1 -race -cover ./...
@echo "Stopping MongoDB..."
docker-compose -f ./tests/docker-compose.yml down
docker-compose -f ./docker-compose.yml down
File renamed without changes.
6 changes: 6 additions & 0 deletions repository.go
Expand Up @@ -213,6 +213,9 @@ func (r *mongoRepository[T]) Update(ctx context.Context, id string, model T) (in
}
return 0, errors.Join(ErrFailedToUpdate, err)
}
if result.MatchedCount == 0 {
return 0, errors.Join(ErrFailedToUpdate, ErrNotFound)
}
return result.ModifiedCount, nil
}

Expand Down Expand Up @@ -256,6 +259,9 @@ func (r *mongoRepository[T]) Delete(ctx context.Context, id string) (int64, erro
}
return 0, errors.Join(ErrFailedToDelete, err)
}
if result.DeletedCount == 0 {
return 0, errors.Join(ErrFailedToDelete, ErrNotFound)
}
return result.DeletedCount, nil
}

Expand Down
15 changes: 14 additions & 1 deletion tests/repository_test.go → repository_test.go
@@ -1,4 +1,4 @@
package tests
package mongorepository_test

import (
"context"
Expand All @@ -20,6 +20,7 @@ func TestRepository(t *testing.T) {
db := setupMongoDB(t)
repo := mongorepository.NewMongoRepository[User](db, "users")

var id string
email := "john@example.com"
user := User{Name: "John Doe", Email: email}

Expand Down Expand Up @@ -138,5 +139,17 @@ func TestRepository(t *testing.T) {
foundUser, err := repo.FindByID(context.Background(), id)
require.ErrorIs(t, err, mongorepository.ErrNotFound)
assert.Empty(t, foundUser)

// Test delete non-existent user
delCount, err = repo.Delete(context.Background(), id)
require.ErrorIs(t, err, mongorepository.ErrNotFound)
assert.Equal(t, int64(0), delCount)
})

// Test try to update non-existent user
t.Run("UpdateNonExistent", func(t *testing.T) {
updCount, err := repo.Update(context.Background(), id, user)
require.ErrorIs(t, err, mongorepository.ErrNotFound)
assert.Equal(t, int64(0), updCount)
})
}
4 changes: 2 additions & 2 deletions tests/utils.go → utils_test.go
@@ -1,4 +1,4 @@
package tests
package mongorepository_test

import (
"context"
Expand All @@ -12,7 +12,7 @@ import (
func getMongoDBURI() string {
uri := os.Getenv("MONGODB_URI")
if uri == "" {
return "mongodb://localhost:27017" // default URI
return "mongodb://username:password@localhost:27017" // default URI
}
return uri
}
Expand Down

0 comments on commit 6259ff0

Please sign in to comment.