Skip to content

Commit

Permalink
Add unit tests for subs
Browse files Browse the repository at this point in the history
  • Loading branch information
zivkovicmilos committed Aug 13, 2024
1 parent f32efe4 commit 91044e0
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 8 deletions.
2 changes: 1 addition & 1 deletion contribs/gnostats/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ type Hub struct {
// NewHub creates a new hub instance
func NewHub() *Hub {
return &Hub{
subs: &subs{},
subs: make(subs),
}
}

Expand Down
14 changes: 7 additions & 7 deletions contribs/gnostats/server/subs.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,32 @@ type (
)

// subscribe creates a new data stream subscription
func (s *subs) subscribe() (xid.ID, dataStream) {
func (s subs) subscribe() (xid.ID, dataStream) {
var (
id = xid.New()
ch = make(dataStream, 1)
)

(*s)[id] = ch
s[id] = ch

return id, ch
}

// unsubscribe removes the given subscription
func (s *subs) unsubscribe(id xid.ID) {
if ch := (*s)[id]; ch != nil {
func (s subs) unsubscribe(id xid.ID) {
if ch := s[id]; ch != nil {
// Close the notification channel
close(ch)
}

// Delete the subscription
delete(*s, id)
delete(s, id)
}

// notify notifies all subscription listeners
func (s *subs) notify(data *proto.DataPoint) {
func (s subs) notify(data *proto.DataPoint) {
// Notify the listeners
for _, ch := range *s {
for _, ch := range s {
select {
case ch <- data:
default:
Expand Down
75 changes: 75 additions & 0 deletions contribs/gnostats/server/subs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package server

import (
"sync"
"testing"
"time"

"github.com/gnolang/gnostats/proto"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestSubs_Subscribe(t *testing.T) {
t.Parallel()

s := make(subs)

id, ch := s.subscribe()
require.NotNil(t, id)
require.NotNil(t, ch)

assert.Len(t, s, 1)
}

func TestSubs_Unsubscribe(t *testing.T) {
t.Parallel()

s := make(subs)

id, _ := s.subscribe()
require.NotNil(t, id)

require.Len(t, s, 1)

s.unsubscribe(id)
assert.Len(t, s, 0)
}

func TestSubs_Notify(t *testing.T) {
t.Parallel()

var (
s = make(subs)
receivedPoint *proto.DataPoint

dataPoint = generateDataPoints(t, 1)[0]
)

id, ch := s.subscribe()
require.NotNil(t, id)
require.NotNil(t, ch)

defer s.unsubscribe(id)

var wg sync.WaitGroup

wg.Add(1)

go func() {
defer wg.Done()

select {
case <-time.After(5 * time.Second):
case receivedPoint = <-ch:
}
}()

s.notify(dataPoint)

wg.Wait()

assert.Equal(t, dataPoint.StaticInfo.Address, receivedPoint.StaticInfo.Address)
assert.Equal(t, dataPoint.StaticInfo.GnoVersion, receivedPoint.StaticInfo.GnoVersion)
assert.Equal(t, dataPoint.StaticInfo.OsVersion, receivedPoint.StaticInfo.OsVersion)
}

0 comments on commit 91044e0

Please sign in to comment.