92 lines
2.4 KiB
Go
92 lines
2.4 KiB
Go
package repository_test
|
|
|
|
import (
|
|
"codeword/internal/models"
|
|
"codeword/internal/repository"
|
|
"context"
|
|
"github.com/stretchr/testify/require"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
"log"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/pioz/faker"
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
const mongoURI = "mongodb://test:test@127.0.0.1:27020/?authMechanism=SCRAM-SHA-256&authSource=admin&directConnection=true"
|
|
|
|
func TestFindByEmail(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
|
|
client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoURI))
|
|
if err != nil {
|
|
log.Fatalf("Failed to connect to MongoDB: %v", err)
|
|
}
|
|
|
|
defer func() {
|
|
if err := client.Disconnect(ctx); err != nil {
|
|
log.Fatalf("Failed to disconnect MongoDB client: %v", err)
|
|
}
|
|
}()
|
|
|
|
if err := client.Ping(ctx, nil); err != nil {
|
|
log.Fatalf("Failed to ping MongoDB: %v", err)
|
|
}
|
|
|
|
db := client.Database("admin")
|
|
|
|
userRepo := repository.NewUserRepository(repository.Deps{Rdb: nil, Mdb: db.Collection("users")})
|
|
|
|
t.Run("FindByEmail - existing user", func(t *testing.T) {
|
|
user, err := userRepo.FindByEmail(ctx, "email@mail.ru")
|
|
assert.NoError(t, err)
|
|
assert.NotNil(t, user)
|
|
assert.Equal(t, "email@mail.ru", user.Email)
|
|
})
|
|
|
|
t.Run("FindByEmail - non-existing user", func(t *testing.T) {
|
|
user, err := userRepo.FindByEmail(ctx, "nonexisting@example.com")
|
|
assert.NoError(t, err)
|
|
assert.Nil(t, user)
|
|
})
|
|
|
|
}
|
|
|
|
func TestStoreRecoveryRecord(t *testing.T) {
|
|
ctx := context.Background()
|
|
|
|
mongoClient, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoURI))
|
|
require.NoError(t, err)
|
|
|
|
defer func() {
|
|
_ = mongoClient.Disconnect(ctx)
|
|
}()
|
|
|
|
database := mongoClient.Database("admin")
|
|
codeword := database.Collection("codeword")
|
|
_ = codeword.Drop(ctx)
|
|
|
|
userRepo := repository.NewCodewordRepository(repository.Deps{Rdb: nil, Mdb: codeword})
|
|
|
|
for i := 0; i < 10; i++ {
|
|
userID := faker.String()
|
|
email := faker.Email()
|
|
key := []byte("test_recovery_key")
|
|
|
|
err = userRepo.StoreRecoveryRecord(ctx, userID, email, key)
|
|
assert.NoError(t, err)
|
|
|
|
var storedRecord models.RecoveryRecord
|
|
err = codeword.FindOne(ctx, bson.M{"user_id": userID}).Decode(&storedRecord)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, email, storedRecord.Email)
|
|
assert.Equal(t, string(key), storedRecord.Key)
|
|
}
|
|
|
|
_ = database.Drop(ctx)
|
|
}
|