consumer_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package kafka
  2. import (
  3. "encoding/binary"
  4. "sarama/mock"
  5. "testing"
  6. )
  7. func TestSimpleConsumer(t *testing.T) {
  8. masterResponses := make(chan []byte, 1)
  9. extraResponses := make(chan []byte)
  10. mockBroker := mock.NewBroker(t, masterResponses)
  11. mockExtra := mock.NewBroker(t, extraResponses)
  12. defer mockBroker.Close()
  13. defer mockExtra.Close()
  14. // return the extra mock as another available broker
  15. response := []byte{
  16. 0x00, 0x00, 0x00, 0x01,
  17. 0x00, 0x00, 0x00, 0x01,
  18. 0x00, 0x09, 'l', 'o', 'c', 'a', 'l', 'h', 'o', 's', 't',
  19. 0x00, 0x00, 0x00, 0x00,
  20. 0x00, 0x00, 0x00, 0x01,
  21. 0x00, 0x00,
  22. 0x00, 0x07, 'm', 'y', 'T', 'o', 'p', 'i', 'c',
  23. 0x00, 0x00, 0x00, 0x01,
  24. 0x00, 0x00,
  25. 0x00, 0x00, 0x00, 0x00,
  26. 0x00, 0x00, 0x00, 0x01,
  27. 0x00, 0x00, 0x00, 0x00,
  28. 0x00, 0x00, 0x00, 0x00}
  29. binary.BigEndian.PutUint32(response[19:], uint32(mockExtra.Port()))
  30. masterResponses <- response
  31. go func() {
  32. for i := 0; i < 10; i++ {
  33. msg := []byte{
  34. 0x00, 0x00, 0x00, 0x01,
  35. 0x00, 0x07, 'm', 'y', 'T', 'o', 'p', 'i', 'c',
  36. 0x00, 0x00, 0x00, 0x01,
  37. 0x00, 0x00, 0x00, 0x00,
  38. 0x00, 0x00,
  39. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  40. 0x00, 0x00, 0x00, 0x1C,
  41. // messageSet
  42. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  43. 0x00, 0x00, 0x00, 0x10,
  44. // message
  45. 0x23, 0x96, 0x4a, 0xf7, // CRC
  46. 0x00,
  47. 0x00,
  48. 0xFF, 0xFF, 0xFF, 0xFF,
  49. 0x00, 0x00, 0x00, 0x02, 0x00, 0xEE}
  50. binary.BigEndian.PutUint64(msg[35:], uint64(i))
  51. extraResponses <- msg
  52. }
  53. extraResponses <- []byte{
  54. 0x00, 0x00, 0x00, 0x01,
  55. 0x00, 0x07, 'm', 'y', 'T', 'o', 'p', 'i', 'c',
  56. 0x00, 0x00, 0x00, 0x01,
  57. 0x00, 0x00, 0x00, 0x00,
  58. 0x00, 0x00,
  59. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  60. 0x00, 0x00, 0x00, 0x00}
  61. }()
  62. client, err := NewClient("clientID", "localhost", mockBroker.Port())
  63. if err != nil {
  64. t.Fatal(err)
  65. }
  66. consumer, err := NewConsumer(client, "myTopic", 0, "myConsumerGroup")
  67. if err != nil {
  68. t.Fatal(err)
  69. }
  70. for i := 0; i < 10; i++ {
  71. select {
  72. case msg := <-consumer.Messages():
  73. if msg.Offset != int64(i) {
  74. t.Error("Incorrect message offset!")
  75. }
  76. case err := <-consumer.Errors():
  77. t.Error(err)
  78. }
  79. }
  80. consumer.Close()
  81. client.Close()
  82. }