forked from cloudfoundry/lager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter_sink_test.go
104 lines (84 loc) · 2.16 KB
/
writer_sink_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package lager_test
import (
"runtime"
"sync"
"github.com/pivotal-golang/lager"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("WriterSink", func() {
const MaxThreads = 100
var sink lager.Sink
var writer *copyWriter
BeforeSuite(func() {
runtime.GOMAXPROCS(MaxThreads)
})
BeforeEach(func() {
writer = NewCopyWriter()
sink = lager.NewWriterSink(writer, lager.INFO)
})
Context("when logging above the minimum log level", func() {
BeforeEach(func() {
sink.Log(lager.INFO, []byte("hello world"))
})
It("writes to the given writer", func() {
Expect(writer.Copy()).To(Equal([]byte("hello world\n")))
})
})
Context("when logging below the minimum log level", func() {
BeforeEach(func() {
sink.Log(lager.DEBUG, []byte("hello world"))
})
It("does not write to the given writer", func() {
Expect(writer.Copy()).To(Equal([]byte{}))
})
})
Context("when logging from multiple threads", func() {
var content = "abcdefg "
BeforeEach(func() {
wg := new(sync.WaitGroup)
for i := 0; i < MaxThreads; i++ {
wg.Add(1)
go func() {
sink.Log(lager.INFO, []byte(content))
wg.Done()
}()
}
wg.Wait()
})
It("writes to the given writer", func() {
expectedBytes := []byte{}
for i := 0; i < MaxThreads; i++ {
expectedBytes = append(expectedBytes, []byte(content)...)
expectedBytes = append(expectedBytes, []byte("\n")...)
}
Expect(writer.Copy()).To(Equal(expectedBytes))
})
})
})
// copyWriter is an INTENTIONALLY UNSAFE writer. Use it to test code that
// should be handling thread safety.
type copyWriter struct {
contents []byte
lock *sync.RWMutex
}
func NewCopyWriter() *copyWriter {
return ©Writer{
contents: []byte{},
lock: new(sync.RWMutex),
}
}
// no, we really mean RLock on write.
func (writer *copyWriter) Write(p []byte) (n int, err error) {
writer.lock.RLock()
defer writer.lock.RUnlock()
writer.contents = append(writer.contents, p...)
return len(p), nil
}
func (writer *copyWriter) Copy() []byte {
writer.lock.Lock()
defer writer.lock.Unlock()
contents := make([]byte, len(writer.contents))
copy(contents, writer.contents)
return contents
}