2019-10-07 22:14:47 +08:00
|
|
|
// Copyright (c) Mainflux
|
2018-08-26 19:15:48 +08:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
2018-08-06 23:06:55 +08:00
|
|
|
package cassandra_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/gocql/gocql"
|
2023-08-11 17:30:25 +08:00
|
|
|
casclient "github.com/mainflux/mainflux/internal/clients/cassandra"
|
2023-06-14 18:40:37 +08:00
|
|
|
mflog "github.com/mainflux/mainflux/logger"
|
2023-08-11 17:30:25 +08:00
|
|
|
"github.com/ory/dockertest/v3"
|
2018-08-06 23:06:55 +08:00
|
|
|
)
|
|
|
|
|
2023-06-14 18:40:37 +08:00
|
|
|
var logger, _ = mflog.New(os.Stdout, mflog.Info.String())
|
2018-08-06 23:06:55 +08:00
|
|
|
|
|
|
|
func TestMain(m *testing.M) {
|
|
|
|
pool, err := dockertest.NewPool("")
|
|
|
|
if err != nil {
|
|
|
|
logger.Error(fmt.Sprintf("Could not connect to docker: %s", err))
|
|
|
|
}
|
|
|
|
|
2023-10-23 21:27:15 +08:00
|
|
|
container, err := pool.Run("cassandra", "3.11.10", []string{})
|
2018-08-06 23:06:55 +08:00
|
|
|
if err != nil {
|
|
|
|
logger.Error(fmt.Sprintf("Could not start container: %s", err))
|
|
|
|
}
|
|
|
|
|
|
|
|
port := container.GetPort("9042/tcp")
|
|
|
|
addr = fmt.Sprintf("%s:%s", addr, port)
|
|
|
|
|
2023-02-21 20:02:57 +08:00
|
|
|
if err = pool.Retry(func() error {
|
2018-08-06 23:06:55 +08:00
|
|
|
if err := createKeyspace([]string{addr}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-08-11 17:30:25 +08:00
|
|
|
session, err := casclient.Connect(casclient.Config{
|
2019-05-16 05:31:41 +08:00
|
|
|
Hosts: []string{addr},
|
|
|
|
Keyspace: keyspace,
|
|
|
|
})
|
2018-08-06 23:06:55 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer session.Close()
|
|
|
|
|
|
|
|
return nil
|
2023-02-21 20:02:57 +08:00
|
|
|
}); err != nil {
|
2023-02-23 03:50:51 +08:00
|
|
|
logger.Fatal(fmt.Sprintf("Could not connect to docker: %s", err))
|
2018-08-06 23:06:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
code := m.Run()
|
|
|
|
|
|
|
|
if err := pool.Purge(container); err != nil {
|
|
|
|
logger.Error(fmt.Sprintf("Could not purge container: %s", err))
|
|
|
|
}
|
|
|
|
|
|
|
|
os.Exit(code)
|
|
|
|
}
|
|
|
|
|
|
|
|
func createKeyspace(hosts []string) error {
|
|
|
|
cluster := gocql.NewCluster(hosts...)
|
|
|
|
cluster.Consistency = gocql.Quorum
|
|
|
|
|
|
|
|
session, err := cluster.CreateSession()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer session.Close()
|
|
|
|
|
|
|
|
keyspaceCQL := fmt.Sprintf(`CREATE KEYSPACE IF NOT EXISTS %s WITH replication =
|
|
|
|
{'class':'SimpleStrategy','replication_factor':'1'}`, keyspace)
|
|
|
|
|
|
|
|
return session.Query(keyspaceCQL).Exec()
|
|
|
|
}
|