async_producer_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package mocks
  2. import (
  3. "fmt"
  4. "testing"
  5. "github.com/Shopify/sarama"
  6. )
  7. type testReporterMock struct {
  8. errors []string
  9. }
  10. func newTestReporterMock() *testReporterMock {
  11. return &testReporterMock{errors: make([]string, 0)}
  12. }
  13. func (trm *testReporterMock) Errorf(format string, args ...interface{}) {
  14. trm.errors = append(trm.errors, fmt.Sprintf(format, args...))
  15. }
  16. func TestMockAsyncProducerImplementsAsyncProducerInterface(t *testing.T) {
  17. var mp interface{} = &AsyncProducer{}
  18. if _, ok := mp.(sarama.AsyncProducer); !ok {
  19. t.Error("The mock producer should implement the sarama.Producer interface.")
  20. }
  21. }
  22. func TestProducerReturnsExpectationsToChannels(t *testing.T) {
  23. config := sarama.NewConfig()
  24. config.Producer.Return.Successes = true
  25. mp := NewAsyncProducer(t, config)
  26. mp.ExpectInputAndSucceed()
  27. mp.ExpectInputAndSucceed()
  28. mp.ExpectInputAndFail(sarama.ErrOutOfBrokers)
  29. mp.Input() <- &sarama.ProducerMessage{Topic: "test 1"}
  30. mp.Input() <- &sarama.ProducerMessage{Topic: "test 2"}
  31. mp.Input() <- &sarama.ProducerMessage{Topic: "test 3"}
  32. msg1 := <-mp.Successes()
  33. msg2 := <-mp.Successes()
  34. err1 := <-mp.Errors()
  35. if msg1.Topic != "test 1" {
  36. t.Error("Expected message 1 to be returned first")
  37. }
  38. if msg2.Topic != "test 2" {
  39. t.Error("Expected message 2 to be returned second")
  40. }
  41. if err1.Msg.Topic != "test 3" || err1.Err != sarama.ErrOutOfBrokers {
  42. t.Error("Expected message 3 to be returned as error")
  43. }
  44. if err := mp.Close(); err != nil {
  45. t.Error(err)
  46. }
  47. }
  48. func TestProducerWithTooFewExpectations(t *testing.T) {
  49. trm := newTestReporterMock()
  50. mp := NewAsyncProducer(trm, nil)
  51. mp.ExpectInputAndSucceed()
  52. mp.Input() <- &sarama.ProducerMessage{Topic: "test"}
  53. mp.Input() <- &sarama.ProducerMessage{Topic: "test"}
  54. if err := mp.Close(); err != nil {
  55. t.Error(err)
  56. }
  57. if len(trm.errors) != 1 {
  58. t.Error("Expected to report an error")
  59. }
  60. }
  61. func TestProducerWithTooManyExpectations(t *testing.T) {
  62. trm := newTestReporterMock()
  63. mp := NewAsyncProducer(trm, nil)
  64. mp.ExpectInputAndSucceed()
  65. mp.ExpectInputAndFail(sarama.ErrOutOfBrokers)
  66. mp.Input() <- &sarama.ProducerMessage{Topic: "test"}
  67. if err := mp.Close(); err != nil {
  68. t.Error(err)
  69. }
  70. if len(trm.errors) != 1 {
  71. t.Error("Expected to report an error")
  72. }
  73. }