chore: add `WaitOnSignaledMessengerResponse` test utility

This commit is contained in:
Patryk Osmaczko 2023-10-20 16:23:02 +02:00 committed by osmaczko
parent fc8ce915af
commit 148721b680
1 changed files with 56 additions and 0 deletions

View File

@ -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 {