github.com/mendersoftware/go-lib-micro@v0.0.0-20240304135804-e8e39c59b148/mongo/migrate/db_test.go (about)

     1  // Copyright 2023 Northern.tech AS
     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 migrate_test
    15  
    16  import (
    17  	"testing"
    18  
    19  	"github.com/stretchr/testify/assert"
    20  	"go.mongodb.org/mongo-driver/bson"
    21  
    22  	. "github.com/mendersoftware/go-lib-micro/mongo/migrate"
    23  	"github.com/mendersoftware/go-lib-micro/store"
    24  )
    25  
    26  func TestGetTenantDbs(t *testing.T) {
    27  	if testing.Short() {
    28  		t.Skip("skipping TestGetTenantDbs in short mode.")
    29  	}
    30  
    31  	baseDb := "servicename"
    32  	testCases := map[string]struct {
    33  		dbs []string
    34  	}{
    35  		"no tenant dbs": {
    36  			dbs: []string{},
    37  		},
    38  		"1 tenant db": {
    39  			dbs: []string{
    40  				baseDb + "-tenant1",
    41  			},
    42  		},
    43  		">1 tenant db": {
    44  			dbs: []string{
    45  				baseDb + "-tenant1",
    46  				baseDb + "-tenant2",
    47  				baseDb + "-tenant3",
    48  			},
    49  		},
    50  	}
    51  	for name := range testCases {
    52  		tc := testCases[name]
    53  		t.Run(name, func(t *testing.T) {
    54  			db.Wipe()
    55  			client := db.Client()
    56  
    57  			// dummy insert on test dbs to create them
    58  			for _, dbname := range tc.dbs {
    59  				_, err := client.Database(dbname).
    60  					Collection("foo").
    61  					InsertOne(db.CTX(), bson.M{"foo": "bar"})
    62  				assert.NoError(t, err)
    63  			}
    64  
    65  			res, err := GetTenantDbs(db.CTX(), client, store.IsTenantDb(baseDb))
    66  			assert.NoError(t, err)
    67  			assert.Equal(t, tc.dbs, res)
    68  		})
    69  	}
    70  }