chore: add `WaitOnSignaledMessengerResponse` test utility
This commit is contained in:
parent
fc8ce915af
commit
148721b680
|
@ -3,6 +3,7 @@ package protocol
|
|||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
|
@ -33,6 +34,61 @@ func WaitOnMessengerResponse(m *Messenger, condition func(*MessengerResponse) bo
|
|||
return response, err
|
||||
}
|
||||
|
||||
type MessengerSignalsHandlerMock struct {
|
||||
MessengerSignalsHandler
|
||||
|
||||
responseChan chan *MessengerResponse
|
||||
}
|
||||
|
||||
func (m *MessengerSignalsHandlerMock) MessengerResponse(response *MessengerResponse) {
|
||||
// Non-blocking send
|
||||
select {
|
||||
case m.responseChan <- response:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MessengerSignalsHandlerMock) MessageDelivered(chatID string, messageID string) {}
|
||||
|
||||
func WaitOnSignaledMessengerResponse(m *Messenger, condition func(*MessengerResponse) bool, errorMessage string) (*MessengerResponse, error) {
|
||||
interval := 500 * time.Millisecond
|
||||
timeoutChan := time.After(10 * time.Second)
|
||||
|
||||
if m.config.messengerSignalsHandler != nil {
|
||||
return nil, errors.New("messengerSignalsHandler already provided/mocked")
|
||||
}
|
||||
|
||||
responseChan := make(chan *MessengerResponse, 1)
|
||||
m.config.messengerSignalsHandler = &MessengerSignalsHandlerMock{
|
||||
responseChan: responseChan,
|
||||
}
|
||||
|
||||
defer func() {
|
||||
m.config.messengerSignalsHandler = nil
|
||||
}()
|
||||
|
||||
for {
|
||||
_, err := m.RetrieveAll()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
select {
|
||||
case r := <-responseChan:
|
||||
if condition(r) {
|
||||
return r, nil
|
||||
}
|
||||
return nil, errors.New(errorMessage)
|
||||
|
||||
case <-timeoutChan:
|
||||
return nil, errors.New("timed out: " + errorMessage)
|
||||
|
||||
default: // No immediate response, rest & loop back to retrieve again
|
||||
time.Sleep(interval)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func FindFirstByContentType(messages []*common.Message, contentType protobuf.ChatMessage_ContentType) *common.Message {
|
||||
for _, message := range messages {
|
||||
if message.ContentType == contentType {
|
||||
|
|
Loading…
Reference in New Issue