mockbroker.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. package sarama
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. "io"
  7. "net"
  8. "reflect"
  9. "strconv"
  10. "sync"
  11. "testing"
  12. "time"
  13. "github.com/davecgh/go-spew/spew"
  14. )
  15. const (
  16. expectationTimeout = 500 * time.Millisecond
  17. )
  18. type requestHandlerFunc func(req *request) (res encoder)
  19. // MockBroker is a mock Kafka broker that is used in unit tests. It is exposed
  20. // to facilitate testing of higher level or specialized consumers and producers
  21. // built on top of Sarama. Note that it does not 'mimic' the Kafka API protocol,
  22. // but rather provides a facility to do that. It takes care of the TCP
  23. // transport, request unmarshaling, response marshaling, and makes it the test
  24. // writer responsibility to program correct according to the Kafka API protocol
  25. // MockBroker behaviour.
  26. //
  27. // MockBroker is implemented as a TCP server listening on a kernel-selected
  28. // localhost port that can accept many connections. It reads Kafka requests
  29. // from that connection and returns responses programmed by the SetHandlerByMap
  30. // function. If a MockBroker receives a request that it has no programmed
  31. // response for, then it returns nothing and the request times out.
  32. //
  33. // A set of MockRequest builders to define mappings used by MockBroker is
  34. // provided by Sarama. But users can develop MockRequests of their own and use
  35. // them along with or instead of the standard ones.
  36. //
  37. // When running tests with MockBroker it is strongly recommended to specify
  38. // a timeout to `go test` so that if the broker hangs waiting for a response,
  39. // the test panics.
  40. //
  41. // It is not necessary to prefix message length or correlation ID to your
  42. // response bytes, the server does that automatically as a convenience.
  43. type MockBroker struct {
  44. brokerID int32
  45. port int32
  46. closing chan none
  47. stopper chan none
  48. expectations chan encoder
  49. listener net.Listener
  50. t *testing.T
  51. latency time.Duration
  52. handler requestHandlerFunc
  53. history []RequestResponse
  54. lock sync.Mutex
  55. }
  56. // RequestResponse represents a Request/Response pair processed by MockBroker.
  57. type RequestResponse struct {
  58. Request requestBody
  59. Response encoder
  60. }
  61. // SetLatency makes broker pause for the specified period every time before
  62. // replying.
  63. func (b *MockBroker) SetLatency(latency time.Duration) {
  64. b.latency = latency
  65. }
  66. // SetHandlerByMap defines mapping of Request types to MockResponses. When a
  67. // request is received by the broker, it looks up the request type in the map
  68. // and uses the found MockResponse instance to generate an appropriate reply.
  69. // If the request type is not found in the map then nothing is sent.
  70. func (b *MockBroker) SetHandlerByMap(handlerMap map[string]MockResponse) {
  71. b.setHandler(func(req *request) (res encoder) {
  72. reqTypeName := reflect.TypeOf(req.body).Elem().Name()
  73. mockResponse := handlerMap[reqTypeName]
  74. if mockResponse == nil {
  75. return nil
  76. }
  77. return mockResponse.For(req.body)
  78. })
  79. }
  80. // BrokerID returns broker ID assigned to the broker.
  81. func (b *MockBroker) BrokerID() int32 {
  82. return b.brokerID
  83. }
  84. // History returns a slice of RequestResponse pairs in the order they were
  85. // processed by the broker. Note that in case of multiple connections to the
  86. // broker the order expected by a test can be different from the order recorded
  87. // in the history, unless some synchronization is implemented in the test.
  88. func (b *MockBroker) History() []RequestResponse {
  89. b.lock.Lock()
  90. history := make([]RequestResponse, len(b.history))
  91. copy(history, b.history)
  92. b.lock.Unlock()
  93. return history
  94. }
  95. // Port returns the TCP port number the broker is listening for requests on.
  96. func (b *MockBroker) Port() int32 {
  97. return b.port
  98. }
  99. // Addr returns the broker connection string in the form "<address>:<port>".
  100. func (b *MockBroker) Addr() string {
  101. return b.listener.Addr().String()
  102. }
  103. // Close terminates the broker blocking until it stops internal goroutines and
  104. // releases all resources.
  105. func (b *MockBroker) Close() {
  106. close(b.expectations)
  107. if len(b.expectations) > 0 {
  108. buf := bytes.NewBufferString(fmt.Sprintf("mockbroker/%d: not all expectations were satisfied! Still waiting on:\n", b.BrokerID()))
  109. for e := range b.expectations {
  110. _, _ = buf.WriteString(spew.Sdump(e))
  111. }
  112. b.t.Error(buf.String())
  113. }
  114. close(b.closing)
  115. <-b.stopper
  116. }
  117. // setHandler sets the specified function as the request handler. Whenever
  118. // a mock broker reads a request from the wire it passes the request to the
  119. // function and sends back whatever the handler function returns.
  120. func (b *MockBroker) setHandler(handler requestHandlerFunc) {
  121. b.lock.Lock()
  122. b.handler = handler
  123. b.lock.Unlock()
  124. }
  125. func (b *MockBroker) serverLoop() {
  126. defer close(b.stopper)
  127. var err error
  128. var conn net.Conn
  129. go func() {
  130. <-b.closing
  131. err := b.listener.Close()
  132. if err != nil {
  133. b.t.Error(err)
  134. }
  135. }()
  136. wg := &sync.WaitGroup{}
  137. i := 0
  138. for conn, err = b.listener.Accept(); err == nil; conn, err = b.listener.Accept() {
  139. wg.Add(1)
  140. go b.handleRequests(conn, i, wg)
  141. i++
  142. }
  143. wg.Wait()
  144. Logger.Printf("*** mockbroker/%d: listener closed, err=%v", b.BrokerID(), err)
  145. }
  146. func (b *MockBroker) handleRequests(conn net.Conn, idx int, wg *sync.WaitGroup) {
  147. defer wg.Done()
  148. defer func() {
  149. _ = conn.Close()
  150. }()
  151. Logger.Printf("*** mockbroker/%d/%d: connection opened", b.BrokerID(), idx)
  152. var err error
  153. abort := make(chan none)
  154. defer close(abort)
  155. go func() {
  156. select {
  157. case <-b.closing:
  158. _ = conn.Close()
  159. case <-abort:
  160. }
  161. }()
  162. resHeader := make([]byte, 8)
  163. for {
  164. req, err := decodeRequest(conn)
  165. if err != nil {
  166. Logger.Printf("*** mockbroker/%d/%d: invalid request: err=%+v, %+v", b.brokerID, idx, err, spew.Sdump(req))
  167. b.serverError(err)
  168. break
  169. }
  170. if b.latency > 0 {
  171. time.Sleep(b.latency)
  172. }
  173. b.lock.Lock()
  174. res := b.handler(req)
  175. b.history = append(b.history, RequestResponse{req.body, res})
  176. b.lock.Unlock()
  177. if res == nil {
  178. Logger.Printf("*** mockbroker/%d/%d: ignored %v", b.brokerID, idx, spew.Sdump(req))
  179. continue
  180. }
  181. Logger.Printf("*** mockbroker/%d/%d: served %v -> %v", b.brokerID, idx, req, res)
  182. encodedRes, err := encode(res)
  183. if err != nil {
  184. b.serverError(err)
  185. break
  186. }
  187. if len(encodedRes) == 0 {
  188. continue
  189. }
  190. binary.BigEndian.PutUint32(resHeader, uint32(len(encodedRes)+4))
  191. binary.BigEndian.PutUint32(resHeader[4:], uint32(req.correlationID))
  192. if _, err = conn.Write(resHeader); err != nil {
  193. b.serverError(err)
  194. break
  195. }
  196. if _, err = conn.Write(encodedRes); err != nil {
  197. b.serverError(err)
  198. break
  199. }
  200. }
  201. Logger.Printf("*** mockbroker/%d/%d: connection closed, err=%v", b.BrokerID(), idx, err)
  202. }
  203. func (b *MockBroker) defaultRequestHandler(req *request) (res encoder) {
  204. select {
  205. case res, ok := <-b.expectations:
  206. if !ok {
  207. return nil
  208. }
  209. return res
  210. case <-time.After(expectationTimeout):
  211. return nil
  212. }
  213. }
  214. func (b *MockBroker) serverError(err error) {
  215. isConnectionClosedError := false
  216. if _, ok := err.(*net.OpError); ok {
  217. isConnectionClosedError = true
  218. } else if err == io.EOF {
  219. isConnectionClosedError = true
  220. } else if err.Error() == "use of closed network connection" {
  221. isConnectionClosedError = true
  222. }
  223. if isConnectionClosedError {
  224. return
  225. }
  226. b.t.Errorf(err.Error())
  227. }
  228. // NewMockBroker launches a fake Kafka broker. It takes a *testing.T as provided by the
  229. // test framework and a channel of responses to use. If an error occurs it is
  230. // simply logged to the *testing.T and the broker exits.
  231. func NewMockBroker(t *testing.T, brokerID int32) *MockBroker {
  232. return NewMockBrokerAddr(t, brokerID, "localhost:0")
  233. }
  234. // NewMockBrokerAddr behaves like newMockBroker but listens on the address you give
  235. // it rather than just some ephemeral port.
  236. func NewMockBrokerAddr(t *testing.T, brokerID int32, addr string) *MockBroker {
  237. var err error
  238. broker := &MockBroker{
  239. closing: make(chan none),
  240. stopper: make(chan none),
  241. t: t,
  242. brokerID: brokerID,
  243. expectations: make(chan encoder, 512),
  244. }
  245. broker.handler = broker.defaultRequestHandler
  246. broker.listener, err = net.Listen("tcp", addr)
  247. if err != nil {
  248. t.Fatal(err)
  249. }
  250. Logger.Printf("*** mockbroker/%d listening on %s\n", brokerID, broker.listener.Addr().String())
  251. _, portStr, err := net.SplitHostPort(broker.listener.Addr().String())
  252. if err != nil {
  253. t.Fatal(err)
  254. }
  255. tmp, err := strconv.ParseInt(portStr, 10, 32)
  256. if err != nil {
  257. t.Fatal(err)
  258. }
  259. broker.port = int32(tmp)
  260. go broker.serverLoop()
  261. return broker
  262. }
  263. func (b *MockBroker) Returns(e encoder) {
  264. b.expectations <- e
  265. }