session_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. // +build all cassandra
  2. package gocql
  3. import (
  4. "context"
  5. "fmt"
  6. "net"
  7. "testing"
  8. )
  9. func TestSessionAPI(t *testing.T) {
  10. cfg := &ClusterConfig{}
  11. s := &Session{
  12. cfg: *cfg,
  13. cons: Quorum,
  14. policy: RoundRobinHostPolicy(),
  15. }
  16. s.pool = cfg.PoolConfig.buildPool(s)
  17. s.executor = &queryExecutor{
  18. pool: s.pool,
  19. policy: s.policy,
  20. }
  21. defer s.Close()
  22. s.SetConsistency(All)
  23. if s.cons != All {
  24. t.Fatalf("expected consistency 'All', got '%v'", s.cons)
  25. }
  26. s.SetPageSize(100)
  27. if s.pageSize != 100 {
  28. t.Fatalf("expected pageSize 100, got %v", s.pageSize)
  29. }
  30. s.SetPrefetch(0.75)
  31. if s.prefetch != 0.75 {
  32. t.Fatalf("expceted prefetch 0.75, got %v", s.prefetch)
  33. }
  34. trace := &traceWriter{}
  35. s.SetTrace(trace)
  36. if s.trace != trace {
  37. t.Fatalf("expected traceWriter '%v',got '%v'", trace, s.trace)
  38. }
  39. qry := s.Query("test", 1)
  40. if v, ok := qry.values[0].(int); !ok {
  41. t.Fatalf("expected qry.values[0] to be an int, got %v", qry.values[0])
  42. } else if v != 1 {
  43. t.Fatalf("expceted qry.values[0] to be 1, got %v", v)
  44. } else if qry.stmt != "test" {
  45. t.Fatalf("expected qry.stmt to be 'test', got '%v'", qry.stmt)
  46. }
  47. boundQry := s.Bind("test", func(q *QueryInfo) ([]interface{}, error) {
  48. return nil, nil
  49. })
  50. if boundQry.binding == nil {
  51. t.Fatal("expected qry.binding to be defined, got nil")
  52. } else if boundQry.stmt != "test" {
  53. t.Fatalf("expected qry.stmt to be 'test', got '%v'", boundQry.stmt)
  54. }
  55. itr := s.executeQuery(qry)
  56. if itr.err != ErrNoConnections {
  57. t.Fatalf("expected itr.err to be '%v', got '%v'", ErrNoConnections, itr.err)
  58. }
  59. testBatch := s.NewBatch(LoggedBatch)
  60. testBatch.Query("test")
  61. err := s.ExecuteBatch(testBatch)
  62. if err != ErrNoConnections {
  63. t.Fatalf("expected session.ExecuteBatch to return '%v', got '%v'", ErrNoConnections, err)
  64. }
  65. s.Close()
  66. if !s.Closed() {
  67. t.Fatal("expected s.Closed() to be true, got false")
  68. }
  69. //Should just return cleanly
  70. s.Close()
  71. err = s.ExecuteBatch(testBatch)
  72. if err != ErrSessionClosed {
  73. t.Fatalf("expected session.ExecuteBatch to return '%v', got '%v'", ErrSessionClosed, err)
  74. }
  75. }
  76. type funcQueryObserver func(context.Context, ObservedQuery)
  77. func (f funcQueryObserver) ObserveQuery(ctx context.Context, o ObservedQuery) {
  78. f(ctx, o)
  79. }
  80. func TestQueryBasicAPI(t *testing.T) {
  81. qry := &Query{}
  82. // Initiate host
  83. ip := "127.0.0.1"
  84. qry.metrics = preFilledQueryMetrics(map[string]*hostMetrics{ip: {Attempts: 0, TotalLatency: 0}})
  85. if qry.Latency() != 0 {
  86. t.Fatalf("expected Query.Latency() to return 0, got %v", qry.Latency())
  87. }
  88. qry.metrics = preFilledQueryMetrics(map[string]*hostMetrics{ip: {Attempts: 2, TotalLatency: 4}})
  89. if qry.Attempts() != 2 {
  90. t.Fatalf("expected Query.Attempts() to return 2, got %v", qry.Attempts())
  91. }
  92. if qry.Latency() != 2 {
  93. t.Fatalf("expected Query.Latency() to return 2, got %v", qry.Latency())
  94. }
  95. qry.AddAttempts(2, &HostInfo{hostname: ip, connectAddress: net.ParseIP(ip), port: 9042})
  96. if qry.Attempts() != 4 {
  97. t.Fatalf("expected Query.Attempts() to return 4, got %v", qry.Attempts())
  98. }
  99. qry.Consistency(All)
  100. if qry.GetConsistency() != All {
  101. t.Fatalf("expected Query.GetConsistency to return 'All', got '%s'", qry.GetConsistency())
  102. }
  103. trace := &traceWriter{}
  104. qry.Trace(trace)
  105. if qry.trace != trace {
  106. t.Fatalf("expected Query.Trace to be '%v', got '%v'", trace, qry.trace)
  107. }
  108. observer := funcQueryObserver(func(context.Context, ObservedQuery) {})
  109. qry.Observer(observer)
  110. if qry.observer == nil { // can't compare func to func, checking not nil instead
  111. t.Fatal("expected Query.QueryObserver to be set, got nil")
  112. }
  113. qry.PageSize(10)
  114. if qry.pageSize != 10 {
  115. t.Fatalf("expected Query.PageSize to be 10, got %v", qry.pageSize)
  116. }
  117. qry.Prefetch(0.75)
  118. if qry.prefetch != 0.75 {
  119. t.Fatalf("expected Query.Prefetch to be 0.75, got %v", qry.prefetch)
  120. }
  121. rt := &SimpleRetryPolicy{NumRetries: 3}
  122. if qry.RetryPolicy(rt); qry.rt != rt {
  123. t.Fatalf("expected Query.RetryPolicy to be '%v', got '%v'", rt, qry.rt)
  124. }
  125. qry.Bind(qry)
  126. if qry.values[0] != qry {
  127. t.Fatalf("expected Query.Values[0] to be '%v', got '%v'", qry, qry.values[0])
  128. }
  129. }
  130. func TestQueryShouldPrepare(t *testing.T) {
  131. toPrepare := []string{"select * ", "INSERT INTO", "update table", "delete from", "begin batch"}
  132. cantPrepare := []string{"create table", "USE table", "LIST keyspaces", "alter table", "drop table", "grant user", "revoke user"}
  133. q := &Query{}
  134. for i := 0; i < len(toPrepare); i++ {
  135. q.stmt = toPrepare[i]
  136. if !q.shouldPrepare() {
  137. t.Fatalf("expected Query.shouldPrepare to return true, got false for statement '%v'", toPrepare[i])
  138. }
  139. }
  140. for i := 0; i < len(cantPrepare); i++ {
  141. q.stmt = cantPrepare[i]
  142. if q.shouldPrepare() {
  143. t.Fatalf("expected Query.shouldPrepare to return false, got true for statement '%v'", cantPrepare[i])
  144. }
  145. }
  146. }
  147. func TestBatchBasicAPI(t *testing.T) {
  148. cfg := &ClusterConfig{RetryPolicy: &SimpleRetryPolicy{NumRetries: 2}}
  149. s := &Session{
  150. cfg: *cfg,
  151. cons: Quorum,
  152. }
  153. defer s.Close()
  154. s.pool = cfg.PoolConfig.buildPool(s)
  155. // Test UnloggedBatch
  156. b := s.NewBatch(UnloggedBatch)
  157. if b.Type != UnloggedBatch {
  158. t.Fatalf("expceted batch.Type to be '%v', got '%v'", UnloggedBatch, b.Type)
  159. } else if b.rt != cfg.RetryPolicy {
  160. t.Fatalf("expceted batch.RetryPolicy to be '%v', got '%v'", cfg.RetryPolicy, b.rt)
  161. }
  162. // Test LoggedBatch
  163. b = s.NewBatch(LoggedBatch)
  164. if b.Type != LoggedBatch {
  165. t.Fatalf("expected batch.Type to be '%v', got '%v'", LoggedBatch, b.Type)
  166. }
  167. ip := "127.0.0.1"
  168. // Test attempts
  169. b.metrics = preFilledQueryMetrics(map[string]*hostMetrics{ip: {Attempts: 1}})
  170. if b.Attempts() != 1 {
  171. t.Fatalf("expected batch.Attempts() to return %v, got %v", 1, b.Attempts())
  172. }
  173. b.AddAttempts(2, &HostInfo{hostname: ip, connectAddress: net.ParseIP(ip), port: 9042})
  174. if b.Attempts() != 3 {
  175. t.Fatalf("expected batch.Attempts() to return %v, got %v", 3, b.Attempts())
  176. }
  177. // Test latency
  178. if b.Latency() != 0 {
  179. t.Fatalf("expected batch.Latency() to be 0, got %v", b.Latency())
  180. }
  181. b.metrics = preFilledQueryMetrics(map[string]*hostMetrics{ip: {Attempts: 1, TotalLatency: 4}})
  182. if b.Latency() != 4 {
  183. t.Fatalf("expected batch.Latency() to return %v, got %v", 4, b.Latency())
  184. }
  185. // Test Consistency
  186. b.Cons = One
  187. if b.GetConsistency() != One {
  188. t.Fatalf("expected batch.GetConsistency() to return 'One', got '%s'", b.GetConsistency())
  189. }
  190. // Test batch.Query()
  191. b.Query("test", 1)
  192. if b.Entries[0].Stmt != "test" {
  193. t.Fatalf("expected batch.Entries[0].Statement to be 'test', got '%v'", b.Entries[0].Stmt)
  194. } else if b.Entries[0].Args[0].(int) != 1 {
  195. t.Fatalf("expected batch.Entries[0].Args[0] to be 1, got %v", b.Entries[0].Args[0])
  196. }
  197. b.Bind("test2", func(q *QueryInfo) ([]interface{}, error) {
  198. return nil, nil
  199. })
  200. if b.Entries[1].Stmt != "test2" {
  201. t.Fatalf("expected batch.Entries[1].Statement to be 'test2', got '%v'", b.Entries[1].Stmt)
  202. } else if b.Entries[1].binding == nil {
  203. t.Fatal("expected batch.Entries[1].binding to be defined, got nil")
  204. }
  205. // Test RetryPolicy
  206. r := &SimpleRetryPolicy{NumRetries: 4}
  207. b.RetryPolicy(r)
  208. if b.rt != r {
  209. t.Fatalf("expected batch.RetryPolicy to be '%v', got '%v'", r, b.rt)
  210. }
  211. if b.Size() != 2 {
  212. t.Fatalf("expected batch.Size() to return 2, got %v", b.Size())
  213. }
  214. }
  215. func TestConsistencyNames(t *testing.T) {
  216. names := map[fmt.Stringer]string{
  217. Any: "ANY",
  218. One: "ONE",
  219. Two: "TWO",
  220. Three: "THREE",
  221. Quorum: "QUORUM",
  222. All: "ALL",
  223. LocalQuorum: "LOCAL_QUORUM",
  224. EachQuorum: "EACH_QUORUM",
  225. Serial: "SERIAL",
  226. LocalSerial: "LOCAL_SERIAL",
  227. LocalOne: "LOCAL_ONE",
  228. }
  229. for k, v := range names {
  230. if k.String() != v {
  231. t.Fatalf("expected '%v', got '%v'", v, k.String())
  232. }
  233. }
  234. }
  235. func TestIsUseStatement(t *testing.T) {
  236. testCases := []struct {
  237. input string
  238. exp bool
  239. }{
  240. {"USE foo", true},
  241. {"USe foo", true},
  242. {"UsE foo", true},
  243. {"Use foo", true},
  244. {"uSE foo", true},
  245. {"uSe foo", true},
  246. {"usE foo", true},
  247. {"use foo", true},
  248. {"SELECT ", false},
  249. {"UPDATE ", false},
  250. {"INSERT ", false},
  251. {"", false},
  252. }
  253. for _, tc := range testCases {
  254. v := isUseStatement(tc.input)
  255. if v != tc.exp {
  256. t.Fatalf("expected %v but got %v for statement %q", tc.exp, v, tc.input)
  257. }
  258. }
  259. }