producer_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package kafka
  2. import (
  3. "encoding/binary"
  4. "sarama/mock"
  5. "testing"
  6. )
  7. func TestSimpleProducer(t *testing.T) {
  8. responses := make(chan []byte, 1)
  9. extraResponses := make(chan []byte)
  10. mockBroker := mock.NewBroker(t, responses)
  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. responses <- 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. binary.BigEndian.PutUint64(msg[23:], uint64(i))
  41. extraResponses <- msg
  42. }
  43. }()
  44. client, err := NewClient("clientID", "localhost", mockBroker.Port())
  45. if err != nil {
  46. t.Fatal(err)
  47. }
  48. producer := NewProducer(client, "myTopic", &RandomPartitioner{})
  49. for i := 0; i < 10; i++ {
  50. err = producer.SendMessage(nil, StringEncoder("ABC THE MESSAGE"))
  51. if err != nil {
  52. t.Error(err)
  53. }
  54. }
  55. client.Close()
  56. }