So i want to test out an API that interacts with Cassandra on my local machine. In my func TestMain(m *testing.M)
function, i want to clear the tables before running the tests. The TestMain
function looks like this...
func TestMain(m *testing.M) {
keyspace = "staging"
cassandra.SetKeyspace(keyspace)
client = http.DefaultClient
// Ensure all tables are empty before tests run
err := ClearAllTables()
if err != nil {
logrus.Errorf("Failed to clear all tables: %v.", err)
os.Exit(1)
}
// Run tests
statusCode := m.Run()
os.Exit(statusCode)
}
The ClearAllTables
function looks like this...
func ClearAllTables() (err error) {
// Create a DB session
session := cassandra.CreateSession()
defer session.Close()
// Get names of all existing tables
tableNameList := []string{"cliques", "users"}
// Remove all rows from each table
var count int
for _, tableName := range tableNameList {
if err := session.Query(`TRUNCATE TABLE ` + tableName).Exec(); err != nil {
return err
}
}
return nil
}
For some reason when i try to TRUNCATE the table, Cassandra times out, and i get the error...
level=error msg="Failed to clear all tables: gocql: no response received from cassandra within timeout period."
This only seems to happen when i test the program. I wrote a snippet of code in the main function that works fine.
func main () {
session := cassandra.CreateSession()
defer session.Close()
if err := session.Query(`TRUNCATE TABLE cliques`).Exec(); err != nil {
return
}
fmt.Println("Table truncated") //works
}
I also wrote a snippet of code that returns some rows from the database, and that also works fine in the main function.
Here is how i create my cassandra session...
// CreateSession connect to a cassandra instance
func CreateSession() *gocql.Session {
// Connect to the cluster
cluster := gocql.NewCluster("127.0.0.1")
cluster.Keyspace = "staging"
cluster.ProtoVersion = 4
cluster.CQLVersion = "3.0.0"
cluster.Consistency = gocql.One
session, err := cluster.CreateSession()
if err != nil {
logrus.Errorf("Failed to connect to Cassandra: %v.", err)
}
return session
}
I'm i missing anything, Why would Cassandra work fine with go run main.go
but doesn't work with go test
?