aboutsummaryrefslogtreecommitdiff
path: root/plugin/dnstap/dnstapio/io_test.go
blob: 80b8047521b9516f95960c7801289c8d291eb3dc (plain) (blame)
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
package dnstapio

import (
	"bytes"
	"sync"
	"testing"
	"time"

	tap "github.com/dnstap/golang-dnstap"
)

type buf struct {
	*bytes.Buffer
	cost time.Duration
}

func (b buf) Write(frame []byte) (int, error) {
	time.Sleep(b.cost)
	return b.Buffer.Write(frame)
}

func (b buf) Close() error {
	return nil
}

func TestRace(t *testing.T) {
	b := buf{&bytes.Buffer{}, 100 * time.Millisecond}
	dio := New(b)
	wg := &sync.WaitGroup{}
	wg.Add(10)
	for i := 0; i < 10; i++ {
		timeout := time.After(time.Second)
		go func() {
			for {
				select {
				case <-timeout:
					wg.Done()
					return
				default:
					time.Sleep(50 * time.Millisecond)
					dio.Dnstap(tap.Dnstap{})
				}
			}
		}()
	}
	wg.Wait()
}

func TestClose(t *testing.T) {
	done := make(chan bool)
	var dio *DnstapIO
	go func() {
		b := buf{&bytes.Buffer{}, 0}
		dio = New(b)
		dio.Close()
		close(done)
	}()
	select {
	case <-done:
	case <-time.After(time.Second):
		t.Fatal("Not closing.")
	}
	func() {
		defer func() {
			if err := recover(); err == nil {
				t.Fatal("Send on closed channel.")
			}
		}()
		dio.Dnstap(tap.Dnstap{})
	}()
}