@@ -15,16 +15,16 @@ func Test_MailboxWorker_EndSignal(t *testing.T) {
1515
1616 sendC := make (chan any )
1717 receiveC := make (chan any )
18- q := NewQueue [ any ]( 0 , 0 )
18+ options := OptionsMailbox {}
1919
20- w := NewMailboxWorker (sendC , receiveC , q )
20+ w := NewMailboxWorker (sendC , receiveC , options )
2121 assert .NotNil (t , w )
2222
2323 // Worker should signal end with empty queue
2424 assert .Equal (t , WorkerEnd , w .DoWork (ContextEnded ()))
2525
2626 // Worker should signal end with non-empty queue
27- q .PushBack (`🌹` )
27+ w . Queue () .PushBack (`🌹` )
2828 assert .Equal (t , WorkerEnd , w .DoWork (ContextEnded ()))
2929}
3030
@@ -181,6 +181,65 @@ func Test_MailboxOptAsChan(t *testing.T) {
181181 })
182182}
183183
184+ // This test asserts that Mailbox will end only after all messages have been received.
185+ func Test_Mailbox_OptEndAferReceivingAll (t * testing.T ) {
186+ t .Parallel ()
187+
188+ const messagesCount = 1000
189+
190+ sendMessages := func (m Mailbox [any ]) {
191+ t .Helper ()
192+
193+ for i := 0 ; i < messagesCount ; i ++ {
194+ assert .NoError (t , m .Send (ContextStarted (), `🥥` ))
195+ }
196+ }
197+ assertGotAllMessages := func (m Mailbox [any ]) {
198+ t .Helper ()
199+
200+ gotMessages := 0
201+
202+ for msg := range m .ReceiveC () {
203+ assert .Equal (t , `🥥` , msg )
204+ gotMessages ++
205+ }
206+
207+ assert .Equal (t , messagesCount , gotMessages )
208+ }
209+
210+ t .Run ("the-best-way" , func (t * testing.T ) {
211+ t .Parallel ()
212+
213+ m := NewMailbox [any ](OptStopAfterReceivingAll ())
214+ m .Start ()
215+ sendMessages (m )
216+
217+ // Stop has to be called in goroutine because Stop is blocking until
218+ // actor (mailbox) has fully ended. And current thread of execution is needed
219+ // to read data from mailbox.
220+ go m .Stop ()
221+
222+ assertGotAllMessages (m )
223+ })
224+
225+ t .Run ("suboptimal-way" , func (t * testing.T ) {
226+ t .Parallel ()
227+
228+ m := NewMailbox [any ](OptStopAfterReceivingAll ())
229+ m .Start ()
230+ sendMessages (m )
231+
232+ // This time we start gorotune which will read all messages from mailbox instead of
233+ // stopping in separate goroutine.
234+ // There are no guaranees that this gorutine will finish after Stop is called, so
235+ // it could be the case that this gorotuine has received all messages from mailbox,
236+ // even before mailbox was stopped. Which wouldn't correctly assert this feature.
237+ go assertGotAllMessages (m )
238+
239+ m .Stop ()
240+ })
241+ }
242+
184243func assertSendReceive (t * testing.T , m Mailbox [any ], val any ) {
185244 t .Helper ()
186245
0 commit comments