github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/daemon/logger/loggerutils/cache/log_cache_test.go (about)

     1  package cache
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/docker/docker/daemon/logger"
    10  	"gotest.tools/v3/assert"
    11  	is "gotest.tools/v3/assert/cmp"
    12  )
    13  
    14  type fakeLogger struct {
    15  	messages chan logger.Message
    16  	close    chan struct{}
    17  }
    18  
    19  func (l *fakeLogger) Log(msg *logger.Message) error {
    20  	select {
    21  	case l.messages <- *msg:
    22  	case <-l.close:
    23  	}
    24  	logger.PutMessage(msg)
    25  	return nil
    26  }
    27  
    28  func (l *fakeLogger) Name() string {
    29  	return "fake"
    30  }
    31  
    32  func (l *fakeLogger) Close() error {
    33  	close(l.close)
    34  	return nil
    35  }
    36  
    37  func TestLog(t *testing.T) {
    38  	cacher := &fakeLogger{make(chan logger.Message), make(chan struct{})}
    39  	l := &loggerWithCache{
    40  		l:     &fakeLogger{make(chan logger.Message, 100), make(chan struct{})},
    41  		cache: cacher,
    42  	}
    43  	defer l.Close()
    44  
    45  	var messages []logger.Message
    46  	for i := 0; i < 100; i++ {
    47  		messages = append(messages, logger.Message{
    48  			Timestamp: time.Now(),
    49  			Line:      append(bytes.Repeat([]byte("a"), 100), '\n'),
    50  		})
    51  	}
    52  
    53  	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
    54  	defer cancel()
    55  
    56  	go func() {
    57  		for _, msg := range messages {
    58  			select {
    59  			case <-ctx.Done():
    60  				return
    61  			default:
    62  			}
    63  
    64  			m := logger.NewMessage()
    65  			dumbCopyMessage(m, &msg)
    66  			l.Log(m)
    67  		}
    68  	}()
    69  
    70  	for _, m := range messages {
    71  		var msg logger.Message
    72  		select {
    73  		case <-ctx.Done():
    74  			t.Fatal("timed out waiting for messages... this is probably a test implementation error")
    75  		case msg = <-cacher.messages:
    76  			assert.Assert(t, is.DeepEqual(msg, m))
    77  		}
    78  	}
    79  }