-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream_test.go
87 lines (74 loc) · 2.05 KB
/
stream_test.go
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
package sense_test
import (
"context"
"fmt"
"io"
"net/http"
"os"
"strings"
"testing"
"github.com/dnesting/sense"
"github.com/dnesting/sense/internal/senseutil"
"github.com/dnesting/sense/realtime"
)
func TestSense(t *testing.T) {
}
func mockForExample() []sense.Option {
type mockMsg = senseutil.RTMsg
ch := make(chan mockMsg)
go func() {
ch <- mockMsg{M: &realtime.Hello{}, E: nil}
ch <- mockMsg{M: &realtime.RealtimeUpdate{W: 590.4}, E: nil}
ch <- mockMsg{M: &realtime.RealtimeUpdate{W: 591.4}, E: nil}
ch <- mockMsg{M: &realtime.RealtimeUpdate{W: 592.4}, E: nil}
ch <- mockMsg{M: &realtime.RealtimeUpdate{W: 593.4}, E: nil} // shouldn't see
close(ch)
}()
return []sense.Option{
sense.WithInternalClient(nil, &senseutil.MockRTClient{Ch: ch}),
sense.WithHttpClient(&http.Client{
Transport: &senseutil.MockTransport{
RT: func(req *http.Request) (*http.Response, error) {
fmt.Fprintln(os.Stderr, req.Method, req.URL)
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"access_token":"fake-token"}`)),
}, nil
},
},
})}
}
func ExampleClient_Stream() {
// instantiate a Sense client (error checking omitted)
client, _ := sense.Connect(
context.Background(),
sense.PasswordCredentials{
Email: "[email protected]",
Password: "pass",
},
mockForExample()...)
// start a stream and collect 3 data points
stopAfter := 3
client.Stream(
context.Background(),
123, // monitor ID to stream events from
func(_ context.Context, msg realtime.Message) error {
switch msg := msg.(type) {
case *realtime.Hello:
fmt.Println("We're online!")
case *realtime.RealtimeUpdate:
fmt.Printf("Power consumption is now: %.1f W\n", msg.W)
stopAfter--
if stopAfter == 0 {
return realtime.Stop
}
}
return nil
})
// Output:
// We're online!
// Power consumption is now: 590.4 W
// Power consumption is now: 591.4 W
// Power consumption is now: 592.4 W
}