sync_producer.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. package mocks
  2. import (
  3. "sync"
  4. "github.com/Shopify/sarama"
  5. )
  6. // SyncProducer implements sarama's SyncProducer interface for testing purposes.
  7. // Before you can use it, you have to set expectations on the mock SyncProducer
  8. // to tell it how to handle calls to SendMessage, so you can easily test success
  9. // and failure scenarios.
  10. type SyncProducer struct {
  11. l sync.Mutex
  12. t ErrorReporter
  13. expectations []*producerExpectation
  14. lastOffset int64
  15. }
  16. // NewSyncProducer instantiates a new SyncProducer mock. The t argument should
  17. // be the *testing.T instance of your test method. An error will be written to it if
  18. // an expectation is violated. The config argument is currently unused, but is
  19. // maintained to be compatible with the async Producer.
  20. func NewSyncProducer(t ErrorReporter, config *sarama.Config) *SyncProducer {
  21. return &SyncProducer{
  22. t: t,
  23. expectations: make([]*producerExpectation, 0),
  24. }
  25. }
  26. ////////////////////////////////////////////////
  27. // Implement SyncProducer interface
  28. ////////////////////////////////////////////////
  29. // SendMessage corresponds with the SendMessage method of sarama's SyncProducer implementation.
  30. // You have to set expectations on the mock producer before calling SendMessage, so it knows
  31. // how to handle them. You can set a function in each expectation so that the message value
  32. // checked by this function and an error is returned if the match fails.
  33. // If there is no more remaining expectation when SendMessage is called,
  34. // the mock producer will write an error to the test state object.
  35. func (sp *SyncProducer) SendMessage(msg *sarama.ProducerMessage) (partition int32, offset int64, err error) {
  36. sp.l.Lock()
  37. defer sp.l.Unlock()
  38. if len(sp.expectations) > 0 {
  39. expectation := sp.expectations[0]
  40. sp.expectations = sp.expectations[1:]
  41. if expectation.CheckFunction != nil {
  42. if val, err := msg.Value.Encode(); err != nil {
  43. sp.t.Errorf("Input message encoding failed: %s", err.Error())
  44. return -1, -1, err
  45. } else {
  46. err := expectation.CheckFunction(val)
  47. if err != nil {
  48. sp.t.Errorf("Check function returned an error: %s", err.Error())
  49. return -1, -1, err
  50. }
  51. }
  52. }
  53. if expectation.Result == errProduceSuccess {
  54. sp.lastOffset++
  55. msg.Offset = sp.lastOffset
  56. return 0, msg.Offset, nil
  57. } else {
  58. return -1, -1, expectation.Result
  59. }
  60. } else {
  61. sp.t.Errorf("No more expectation set on this mock producer to handle the input message.")
  62. return -1, -1, errOutOfExpectations
  63. }
  64. }
  65. // SendMessages corresponds with the SendMessages method of sarama's SyncProducer implementation.
  66. // You have to set expectations on the mock producer before calling SendMessages, so it knows
  67. // how to handle them. If there is no more remaining expectations when SendMessages is called,
  68. // the mock producer will write an error to the test state object.
  69. func (sp *SyncProducer) SendMessages(msgs []*sarama.ProducerMessage) error {
  70. sp.l.Lock()
  71. defer sp.l.Unlock()
  72. if len(sp.expectations) >= len(msgs) {
  73. expectations := sp.expectations[0 : len(msgs)-1]
  74. sp.expectations = sp.expectations[len(msgs):]
  75. for _, expectation := range expectations {
  76. if expectation.Result != errProduceSuccess {
  77. return expectation.Result
  78. }
  79. }
  80. return nil
  81. } else {
  82. sp.t.Errorf("Insufficient expectations set on this mock producer to handle the input messages.")
  83. return errOutOfExpectations
  84. }
  85. }
  86. // Close corresponds with the Close method of sarama's SyncProducer implementation.
  87. // By closing a mock syncproducer, you also tell it that no more SendMessage calls will follow,
  88. // so it will write an error to the test state if there's any remaining expectations.
  89. func (sp *SyncProducer) Close() error {
  90. sp.l.Lock()
  91. defer sp.l.Unlock()
  92. if len(sp.expectations) > 0 {
  93. sp.t.Errorf("Expected to exhaust all expectations, but %d are left.", len(sp.expectations))
  94. }
  95. return nil
  96. }
  97. ////////////////////////////////////////////////
  98. // Setting expectations
  99. ////////////////////////////////////////////////
  100. // ExpectSendMessageWithCheckerFunctionAndSucceed sets an expectation on the mock producer that SendMessage
  101. // will be called. The mock producer will first call the given function to check the message value.
  102. // It will cascade the error of the function, if any, or handle the message as if it produced
  103. // successfully, i.e. by returning a valid partition, and offset, and a nil error.
  104. func (sp *SyncProducer) ExpectSendMessageWithCheckerFunctionAndSucceed(cf ValueChecker) {
  105. sp.l.Lock()
  106. defer sp.l.Unlock()
  107. sp.expectations = append(sp.expectations, &producerExpectation{Result: errProduceSuccess, CheckFunction: cf})
  108. }
  109. // ExpectSendMessageAndFail sets an expectation on the mock producer that SendMessage will be
  110. // called. The mock producer will first call the given function to check the message value.
  111. // It will cascade the error of the function, if any, or handle the message as if it failed
  112. // to produce successfully, i.e. by returning the provided error.
  113. func (sp *SyncProducer) ExpectSendMessageWithCheckerFunctionAndFail(cf ValueChecker, err error) {
  114. sp.l.Lock()
  115. defer sp.l.Unlock()
  116. sp.expectations = append(sp.expectations, &producerExpectation{Result: err, CheckFunction: cf})
  117. }
  118. // ExpectSendMessageAndSucceed sets an expectation on the mock producer that SendMessage will be
  119. // called. The mock producer will handle the message as if it produced successfully, i.e. by
  120. // returning a valid partition, and offset, and a nil error.
  121. func (sp *SyncProducer) ExpectSendMessageAndSucceed() {
  122. sp.ExpectSendMessageWithCheckerFunctionAndSucceed(nil)
  123. }
  124. // ExpectSendMessageAndFail sets an expectation on the mock producer that SendMessage will be
  125. // called. The mock producer will handle the message as if it failed to produce
  126. // successfully, i.e. by returning the provided error.
  127. func (sp *SyncProducer) ExpectSendMessageAndFail(err error) {
  128. sp.ExpectSendMessageWithCheckerFunctionAndFail(nil, err)
  129. }