go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/simutil/event_source_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package simutil
     9  
    10  import (
    11  	"context"
    12  	"fmt"
    13  	"sync"
    14  	"sync/atomic"
    15  	"testing"
    16  	"time"
    17  
    18  	"go.charczuk.com/sdk/assert"
    19  )
    20  
    21  type testEvent string
    22  
    23  func Test_EventSource_simulation(t *testing.T) {
    24  	var ordinal uint64
    25  	es := &EventSource[testEvent]{
    26  		Count:    100,
    27  		Interval: EventEvery(time.Second),
    28  		EventFactory: func(_ context.Context) testEvent {
    29  			v := atomic.AddUint64(&ordinal, 1)
    30  			return testEvent(fmt.Sprintf("event-%d", v))
    31  		},
    32  	}
    33  
    34  	ctx, cancel := context.WithCancel(context.Background())
    35  	defer cancel()
    36  
    37  	output := es.Start(ctx, false /*NOT realtime*/)
    38  	var seenEvents []Event[testEvent]
    39  	readwg := sync.WaitGroup{}
    40  	readwg.Add(100)
    41  	ReadEvents(ctx, output, func(_ context.Context, e Event[testEvent]) {
    42  		defer func() {
    43  			readwg.Done()
    44  		}()
    45  		seenEvents = append(seenEvents, e)
    46  	})
    47  	es.Wait()
    48  	readwg.Wait()
    49  
    50  	assert.ItsLen(t, seenEvents, 100)
    51  	assert.ItsEqual(t, "event-1", seenEvents[0].Event)
    52  	assert.ItsEqual(t, "event-2", seenEvents[1].Event)
    53  	assert.ItsEqual(t, "event-3", seenEvents[2].Event)
    54  	assert.ItsEqual(t, "event-4", seenEvents[3].Event)
    55  }