Преглед изворни кода

Added code to output an error on CreateSession when the user provides an
empty array of hosts.

Added code to the test suite to make sure the issue does not appear
again in the future.

Phillip Couto пре 12 година
родитељ
комит
49545d685d
2 измењених фајлова са 31 додато и 5 уклоњено
  1. 15 2
      cluster.go
  2. 16 3
      gocql_test/main.go

+ 15 - 2
cluster.go

@@ -10,6 +10,7 @@ import (
 	"strings"
 	"sync"
 	"time"
+	"errors"
 )
 
 // ClusterConfig is a struct to configure the default cluster implementation
@@ -52,7 +53,15 @@ func NewCluster(hosts ...string) *ClusterConfig {
 
 // CreateSession initializes the cluster based on this config and returns a
 // session object that can be used to interact with the database.
-func (cfg *ClusterConfig) CreateSession() *Session {
+func (cfg *ClusterConfig) CreateSession() (*Session,error) {
+
+	//Check that hosts in the ClusterConfig is not empty
+	if cfg.Hosts == nil {
+		return nil,ErrNoHosts 
+	} else if len(cfg.Hosts) < 1 {
+		return nil,ErrNoHosts
+	}
+	
 	impl := &clusterImpl{
 		cfg:      *cfg,
 		hostPool: NewRoundRobin(),
@@ -74,7 +83,7 @@ func (cfg *ClusterConfig) CreateSession() *Session {
 	impl.wgStart.Wait()
 	s := NewSession(impl)
 	s.SetConsistency(cfg.Consistency)
-	return s
+	return s,nil
 }
 
 type clusterImpl struct {
@@ -223,3 +232,7 @@ func (c *clusterImpl) Close() {
 		}
 	})
 }
+
+var (
+	ErrNoHosts = errors.New("no hosts provided")
+)

+ 16 - 3
gocql_test/main.go

@@ -18,12 +18,12 @@ import (
 var cluster *gocql.ClusterConfig
 var session *gocql.Session
 
-func init() {
+func init(){
 	cluster = gocql.NewCluster("127.0.0.1")
 	// uncomment the following two lines if you want to use Cassandra 1.2
 	// cluster.ProtoVersion = 1
 	// cluster.CQLVersion = "3.0.0"
-	session = cluster.CreateSession()
+	session,_ = cluster.CreateSession()
 }
 
 type Page struct {
@@ -56,7 +56,7 @@ func initSchema() error {
 	time.Sleep(15 * time.Second)
 	log.Println("If there were error messages that an address cannot be assigned then the test failed.")
 	cluster.Keyspace = "gocql_test"
-	session = cluster.CreateSession()
+	session,_ = cluster.CreateSession()
 
 	if err := session.Query(`CREATE TABLE page (
 			title       varchar,
@@ -141,7 +141,20 @@ func getPage(title string, revid uuid.UUID) (*Page, error) {
 	return p, err
 }
 
+//This test checks to make sure a valid error and a nil reference to
+//a session are returned when an empty array of hosts are provided
+//to the cluster configuration
+func TestEmptyHosts () error{
+	empty := make([]string,0)
+	cfg := gocql.NewCluster(empty...)
+	_,err := cfg.CreateSession()
+	return err
+}
+
 func main() {
+	if err := TestEmptyHosts(); err == nil {
+		log.Fatal("Failed to error when empty host list is provided.")
+	}
 	if err := initSchema(); err != nil {
 		log.Fatal("initSchema: ", err)
 	}