package main import ( "html/template" "io" "log" "sync" "testing" "github.com/probakowski/go-satel" "github.com/stretchr/testify/assert" ) type MockSender struct { messages []GenericMessage } func (self *MockSender) Send(msg GenericMessage, tpl *template.Template) error { self.messages = append(self.messages, msg) return nil } type MockSleeper struct { ch *chan<- interface{} callCount int } func (self *MockSleeper) Sleep(ch chan<- interface{}) { if self.ch == nil { self.ch = &ch } self.callCount += 1 } type FakeChatId struct { FakeId int64 } func (self FakeChatId) GetTgIds() *[]int64 { return nil } var ( messageTest1 = satel.Event{Type: satel.ArmedPartition, Index: 1, Value: true} messageTest2 = satel.Event{Type: satel.ArmedPartition, Index: 2, Value: true} messageTest3 = satel.Event{Type: satel.ArmedPartition, Index: 3, Value: true} messageTest4 = satel.Event{Type: satel.ArmedPartition, Index: 4, Value: true} messageTest5 = satel.Event{Type: satel.ArmedPartition, Index: 5, Value: true} messageTest6 = satel.Event{Type: satel.ArmedPartition, Index: 6, Value: true} ) func TestMessageThrottling(t *testing.T) { testEvents := make(chan GenericMessage) wg := sync.WaitGroup{} mockSender := MockSender{make([]GenericMessage, 0)} mockSleeper := MockSleeper{nil, 0} Consume(SendToTg(tgSenderWorker(testEvents, &wg, &mockSleeper, log.New(io.Discard, "", log.Ltime)), &mockSender, &wg, log.New(io.Discard, "", log.Ltime), nil)) testEvents <- GenericMessage{TgChatId{123}, []MsgContent{{messageTest1}}} testEvents <- GenericMessage{TgChatId{124}, []MsgContent{{messageTest3}}} testEvents <- GenericMessage{TgChatId{123}, []MsgContent{{messageTest2}}} testEvents <- GenericMessage{TgChatId{124}, []MsgContent{{messageTest4}}} testEvents <- GenericMessage{FakeChatId{123}, []MsgContent{{messageTest6}}} assert.Equal(t, 1, mockSleeper.callCount) *mockSleeper.ch <- nil assert.Equal(t, 1, mockSleeper.callCount) testEvents <- GenericMessage{TgChatId{123}, []MsgContent{{messageTest5}}} close(testEvents) wg.Wait() assert.Equal(t, 2, mockSleeper.callCount) assert.Len(t, mockSender.messages, 4) assert.Contains(t, mockSender.messages, GenericMessage{TgChatId{123}, []MsgContent{{messageTest1}, {messageTest2}}}) assert.Contains(t, mockSender.messages, GenericMessage{TgChatId{124}, []MsgContent{{messageTest3}, {messageTest4}}}) assert.Contains(t, mockSender.messages, GenericMessage{FakeChatId{123}, []MsgContent{{messageTest6}}}) }