2023-04-10 15:36:59 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2020-09-28 14:13:10 +00:00
|
|
|
package stream
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
2022-03-15 12:42:43 +00:00
|
|
|
"github.com/hashicorp/nomad/ci"
|
2020-09-28 14:13:10 +00:00
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
)
|
|
|
|
|
|
|
|
type testObj struct {
|
|
|
|
Name string `json:"name"`
|
|
|
|
}
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
func TestJsonStream(t *testing.T) {
|
2022-03-15 12:42:43 +00:00
|
|
|
ci.Parallel(t)
|
2020-09-28 14:13:10 +00:00
|
|
|
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
defer cancel()
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
s := NewJsonStream(ctx, 1*time.Second)
|
|
|
|
out := s.OutCh()
|
2020-09-28 14:13:10 +00:00
|
|
|
|
|
|
|
require.NoError(t, s.Send(testObj{Name: "test"}))
|
|
|
|
|
2021-05-21 17:17:07 +00:00
|
|
|
initialHeartbeat := <-out
|
|
|
|
require.Equal(t, []byte(`{}`), initialHeartbeat.Data)
|
2020-09-28 14:13:10 +00:00
|
|
|
|
2021-05-21 17:17:07 +00:00
|
|
|
testMessage1 := <-out
|
|
|
|
require.Equal(t, []byte(`{"name":"test"}`), testMessage1.Data)
|
2020-09-28 14:13:10 +00:00
|
|
|
|
|
|
|
select {
|
2020-10-08 18:27:52 +00:00
|
|
|
case msg := <-out:
|
|
|
|
require.Failf(t, "Did not expect another message", "%#v", msg)
|
2020-09-28 14:13:10 +00:00
|
|
|
case <-time.After(100 * time.Millisecond):
|
|
|
|
}
|
2020-10-08 18:27:52 +00:00
|
|
|
|
|
|
|
require.NoError(t, s.Send(testObj{Name: "test2"}))
|
|
|
|
|
2021-05-21 17:17:07 +00:00
|
|
|
testMessage2 := <-out
|
|
|
|
require.Equal(t, []byte(`{"name":"test2"}`), testMessage2.Data)
|
2020-09-28 14:13:10 +00:00
|
|
|
}
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
func TestJson_Send_After_Stop(t *testing.T) {
|
2022-03-15 12:42:43 +00:00
|
|
|
ci.Parallel(t)
|
2020-09-28 14:13:10 +00:00
|
|
|
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
defer cancel()
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
s := NewJsonStream(ctx, 1*time.Second)
|
2020-09-28 14:13:10 +00:00
|
|
|
|
|
|
|
// stop the stream
|
|
|
|
cancel()
|
|
|
|
|
|
|
|
time.Sleep(10 * time.Millisecond)
|
|
|
|
require.Error(t, s.Send(testObj{}))
|
|
|
|
}
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
func TestJson_HeartBeat(t *testing.T) {
|
2022-03-15 12:42:43 +00:00
|
|
|
ci.Parallel(t)
|
2020-09-28 14:13:10 +00:00
|
|
|
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
defer cancel()
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
s := NewJsonStream(ctx, 10*time.Millisecond)
|
2020-09-28 14:13:10 +00:00
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
out := s.OutCh()
|
2020-09-28 14:13:10 +00:00
|
|
|
heartbeat := <-out
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
require.Equal(t, JsonHeartbeat, heartbeat)
|
2020-09-28 14:13:10 +00:00
|
|
|
}
|