mongodb_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2020 gorse Project Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package data
  15. import (
  16. "context"
  17. "os"
  18. "testing"
  19. "github.com/stretchr/testify/suite"
  20. )
  21. var (
  22. mongoUri string
  23. )
  24. func init() {
  25. // get environment variables
  26. env := func(key, defaultValue string) string {
  27. if value := os.Getenv(key); value != "" {
  28. return value
  29. }
  30. return defaultValue
  31. }
  32. mongoUri = env("MONGO_URI", "mongodb://root:password@127.0.0.1:27017/")
  33. }
  34. type MongoTestSuite struct {
  35. baseTestSuite
  36. }
  37. func (suite *MongoTestSuite) SetupSuite() {
  38. ctx := context.Background()
  39. var err error
  40. // create database
  41. suite.Database, err = Open(mongoUri, "gorse_")
  42. suite.NoError(err)
  43. dbName := "gorse_data_test"
  44. databaseComm := suite.getMongoDB()
  45. err = databaseComm.client.Database(dbName).Drop(ctx)
  46. if err == nil {
  47. suite.T().Log("delete existed database:", dbName)
  48. }
  49. err = suite.Database.Close()
  50. suite.NoError(err)
  51. // create schema
  52. suite.Database, err = Open(mongoUri+dbName+"?authSource=admin&connect=direct", "gorse_")
  53. suite.NoError(err)
  54. err = suite.Database.Init()
  55. suite.NoError(err)
  56. }
  57. func (suite *MongoTestSuite) getMongoDB() *MongoDB {
  58. var mongoDatabase *MongoDB
  59. var ok bool
  60. mongoDatabase, ok = suite.Database.(*MongoDB)
  61. suite.True(ok)
  62. return mongoDatabase
  63. }
  64. func TestMongo(t *testing.T) {
  65. suite.Run(t, new(MongoTestSuite))
  66. }