github.com/blend/go-sdk@v1.20220411.3/logger/worker_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package logger
     9  
    10  import (
    11  	"context"
    12  	"sync"
    13  	"testing"
    14  	"time"
    15  
    16  	"github.com/blend/go-sdk/assert"
    17  )
    18  
    19  func TestWorker(t *testing.T) {
    20  	assert := assert.New(t)
    21  
    22  	wg := sync.WaitGroup{}
    23  	wg.Add(1)
    24  	var didFire bool
    25  	w := NewWorker(func(_ context.Context, e Event) {
    26  		defer wg.Done()
    27  		didFire = true
    28  
    29  		typed, isTyped := e.(MessageEvent)
    30  		assert.True(isTyped)
    31  		assert.Equal("test", typed.Text)
    32  	})
    33  
    34  	go func() { _ = w.Start() }()
    35  	<-w.NotifyStarted()
    36  	defer func() { _ = w.Stop() }()
    37  
    38  	w.Work <- EventWithContext{context.Background(), NewMessageEvent(Info, "test")}
    39  	wg.Wait()
    40  
    41  	assert.True(didFire)
    42  }
    43  
    44  func TestWorkerStop(t *testing.T) {
    45  	assert := assert.New(t)
    46  
    47  	wg := sync.WaitGroup{}
    48  	wg.Add(4)
    49  	var didFire bool
    50  	w := NewWorker(func(ctx context.Context, e Event) {
    51  		defer wg.Done()
    52  		didFire = true
    53  	})
    54  
    55  	go func() { _ = w.Start() }()
    56  	<-w.NotifyStarted()
    57  
    58  	w.Work <- EventWithContext{Event: NewMessageEvent(Info, "test1")}
    59  	w.Work <- EventWithContext{Event: NewMessageEvent(Info, "test2")}
    60  	w.Work <- EventWithContext{Event: NewMessageEvent(Info, "test3")}
    61  	w.Work <- EventWithContext{Event: NewMessageEvent(Info, "test4")}
    62  
    63  	go func() {
    64  		ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
    65  		defer cancel()
    66  		_ = w.StopContext(ctx)
    67  	}()
    68  	wg.Wait()
    69  
    70  	assert.True(didFire)
    71  }