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 105 106 107 108 109 110 111 112 113
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package sse
import (
"errors"
"runtime"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func wait(ch chan *Event, duration time.Duration) ([]byte, error) {
var err error
var msg []byte
select {
case event := <-ch:
msg = event.Data
case <-time.After(duration):
err = errors.New("timeout")
}
return msg, err
}
func waitEvent(ch chan *Event, duration time.Duration) (*Event, error) {
select {
case event := <-ch:
return event, nil
case <-time.After(duration):
return nil, errors.New("timeout")
}
}
func TestServerCreateStream(t *testing.T) {
s := New()
defer s.Close()
s.CreateStream("test")
assert.NotNil(t, s.getStream("test"))
}
func TestServerWithCallback(t *testing.T) {
funcA := func(string, *Subscriber) {}
funcB := func(string, *Subscriber) {}
s := NewWithCallback(funcA, funcB)
defer s.Close()
assert.NotNil(t, s.OnSubscribe)
assert.NotNil(t, s.OnUnsubscribe)
}
func TestServerCreateExistingStream(t *testing.T) {
s := New()
defer s.Close()
s.CreateStream("test")
numGoRoutines := runtime.NumGoroutine()
s.CreateStream("test")
assert.NotNil(t, s.getStream("test"))
assert.Equal(t, numGoRoutines, runtime.NumGoroutine())
}
func TestServerRemoveStream(t *testing.T) {
s := New()
defer s.Close()
s.CreateStream("test")
s.RemoveStream("test")
assert.Nil(t, s.getStream("test"))
}
func TestServerRemoveNonExistentStream(t *testing.T) {
s := New()
defer s.Close()
s.RemoveStream("test")
assert.NotPanics(t, func() { s.RemoveStream("test") })
}
func TestServerExistingStreamPublish(t *testing.T) {
s := New()
defer s.Close()
s.CreateStream("test")
stream := s.getStream("test")
sub := stream.addSubscriber(0, nil)
s.Publish("test", &Event{Data: []byte("test")})
msg, err := wait(sub.connection, time.Second*1)
require.Nil(t, err)
assert.Equal(t, []byte(`test`), msg)
}
func TestServerNonExistentStreamPublish(t *testing.T) {
s := New()
defer s.Close()
s.RemoveStream("test")
assert.NotPanics(t, func() { s.Publish("test", &Event{Data: []byte("test")}) })
}
|