fix: add mutex to fix race conditions for consumers

This commit is contained in:
2022-06-16 11:52:48 +02:00
parent 7db3319133
commit 1e4b943789
5 changed files with 23 additions and 29 deletions
+13 -11
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2020 Unbound Software Development Svenska AB
// Copyright (c) 2022 Unbound Software Development Svenska AB
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
@@ -21,19 +21,24 @@ package apex
import (
"fmt"
"github.com/apex/log"
"github.com/sanity-io/litter"
"sync"
"testing"
"github.com/apex/log"
"github.com/stretchr/testify/assert"
)
// Mock has a Logger for use in unit-testing
type Mock struct {
*sync.RWMutex
Logger log.Interface
Logged []string
}
// HandleLog stores the logged entries to be able to check them later
func (m *Mock) HandleLog(entry *log.Entry) error {
m.Lock()
defer m.Unlock()
m.Logged = append(m.Logged, fmt.Sprintf("%s: %s", entry.Level.String(), entry.Message))
return nil
}
@@ -43,7 +48,8 @@ var _ log.Handler = &Mock{}
// New instantiates a new Mock and sets the log.Handler to it
func New() *Mock {
mock := &Mock{
Logger: log.Log,
RWMutex: &sync.RWMutex{},
Logger: log.Log,
}
log.SetHandler(mock)
return mock
@@ -52,11 +58,7 @@ func New() *Mock {
// Check verifies that the application has logged the expected strings
func (m *Mock) Check(t testing.TB, wantLogged []string) {
t.Helper()
if len(m.Logged) != 0 || len(wantLogged) != 0 {
got := litter.Sdump(m.Logged)
want := litter.Sdump(wantLogged)
if got != want {
t.Errorf("Logger() got %s, want %s", got, want)
}
}
m.RLock()
defer m.RUnlock()
assert.Equal(t, wantLogged, m.Logged)
}