aboutsummaryrefslogtreecommitdiff
path: root/playground/socket/socket_test.go
blob: d410afea8756c1e406327bc0a18647c15a105b3e (plain)
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
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package socket

import (
	"testing"
	"time"
)

func TestBuffer(t *testing.T) {
	afterChan := make(chan time.Time)
	ch := make(chan *Message)
	go func() {
		ch <- &Message{Kind: "err", Body: "a"}
		ch <- &Message{Kind: "err", Body: "b"}
		ch <- &Message{Kind: "out", Body: "1"}
		ch <- &Message{Kind: "out", Body: "2"}
		afterChan <- time.Time{} // value itself doesn't matter
		ch <- &Message{Kind: "out", Body: "3"}
		ch <- &Message{Kind: "out", Body: "4"}
		close(ch)
	}()

	var ms []*Message
	timeAfter := func(d time.Duration) <-chan time.Time {
		return afterChan
	}
	for m := range buffer(ch, timeAfter) {
		ms = append(ms, m)
	}
	if len(ms) != 3 {
		t.Fatalf("got %v messages, want 3", len(ms))
	}
	if g, w := ms[0].Body, "ab"; g != w {
		t.Errorf("message 0 body = %q, want %q", g, w)
	}
	if g, w := ms[1].Body, "12"; g != w {
		t.Errorf("message 1 body = %q, want %q", g, w)
	}
	if g, w := ms[2].Body, "34"; g != w {
		t.Errorf("message 2 body = %q, want %q", g, w)
	}
}

type killRecorder chan struct{}

func (k killRecorder) Kill() { close(k) }

func TestLimiter(t *testing.T) {
	ch := make(chan *Message)
	go func() {
		var m Message
		for i := 0; i < msgLimit+10; i++ {
			ch <- &m
		}
		ch <- &Message{Kind: "end"}
	}()

	kr := make(killRecorder)
	n := 0
	for m := range limiter(ch, kr) {
		n++
		if n > msgLimit && m.Kind != "end" {
			t.Errorf("received non-end message after limit")
		}
	}
	if n != msgLimit+1 {
		t.Errorf("received %v messages, want %v", n, msgLimit+1)
	}
	<-kr
}