diff --git a/internal/infrastructure/mongo/asset_test.go b/internal/infrastructure/mongo/asset_test.go index bc188fe0..135683df 100644 --- a/internal/infrastructure/mongo/asset_test.go +++ b/internal/infrastructure/mongo/asset_test.go @@ -2,27 +2,15 @@ package mongo import ( "context" - "os" "testing" "time" - "github.com/reearth/reearth-backend/internal/infrastructure/mongo/mongodoc" "github.com/reearth/reearth-backend/pkg/asset" "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" - "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" ) func TestFindByID(t *testing.T) { - // Skip unit testing if "REEARTH_DB" is not configured - // See details: https://github.com/reearth/reearth/issues/273 - db := os.Getenv("REEARTH_DB") - if db == "" { - return - } - tests := []struct { Name string Expected struct { @@ -48,12 +36,7 @@ func TestFindByID(t *testing.T) { }, } - c, _ := mongo.Connect( - context.Background(), - options.Client(). - ApplyURI(db). - SetConnectTimeout(time.Second*10), - ) + initDB := connect(t) for _, tc := range tests { tc := tc @@ -61,18 +44,14 @@ func TestFindByID(t *testing.T) { t.Run(tc.Name, func(t *testing.T) { t.Parallel() - database, _ := uuid.New() - client := mongodoc.NewClient(string(database[:]), c) - repo := NewAsset(client) + client, dropDB := initDB() + defer dropDB() + repo := NewAsset(client) ctx := context.Background() err := repo.Save(ctx, tc.Expected.Asset) assert.NoError(t, err) - defer func() { - _ = c.Database(string(database[:])).Drop(ctx) - }() - got, err := repo.FindByID(ctx, tc.Expected.Asset.ID()) assert.NoError(t, err) assert.Equal(t, tc.Expected.Asset.ID(), got.ID()) diff --git a/internal/infrastructure/mongo/mongo_test.go b/internal/infrastructure/mongo/mongo_test.go new file mode 100644 index 00000000..0fb72e79 --- /dev/null +++ b/internal/infrastructure/mongo/mongo_test.go @@ -0,0 +1,42 @@ +package mongo + +import ( + "context" + "os" + "testing" + "time" + + "github.com/reearth/reearth-backend/internal/infrastructure/mongo/mongodoc" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" +) + +func connect(t *testing.T) func() (*mongodoc.Client, func()) { + t.Helper() + + // Skip unit testing if "REEARTH_DB" is not configured + // See details: https://github.com/reearth/reearth/issues/273 + db := os.Getenv("REEARTH_DB") + if db == "" { + t.SkipNow() + return nil + } + + c, _ := mongo.Connect( + context.Background(), + options.Client(). + ApplyURI(db). + SetConnectTimeout(time.Second*10), + ) + + return func() (*mongodoc.Client, func()) { + database, _ := uuid.New() + databaseName := "reearth-test-" + string(database[:]) + client := mongodoc.NewClient(databaseName, c) + + return client, func() { + _ = c.Database(databaseName).Drop(context.Background()) + } + } +}