forked from bugst/go-serial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial_windows_test.go
115 lines (95 loc) · 2.22 KB
/
serial_windows_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
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
114
115
package serial
import (
"context"
"errors"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func openTestPort(t *testing.T) (Port, error) {
ports, err := GetPortsList()
if err != nil || len(ports) == 0 {
t.SkipNow()
}
mode := Mode{
BaudRate: 115200,
DataBits: 8,
Parity: NoParity,
StopBits: OneStopBit,
}
return Open(ports[0], &mode)
}
func TestOpenClose(t *testing.T) {
// prevent port from being busy in other tests
defer time.Sleep(time.Millisecond)
port, err := openTestPort(t)
require.NoError(t, err)
port.Close()
}
func TestOpenReadClosed(t *testing.T) {
// prevent port from being busy in other tests
defer time.Sleep(time.Millisecond)
port, err := openTestPort(t)
require.NoError(t, err)
defer port.Close()
done := make(chan struct{})
var readErr error
go func() {
buf := make([]byte, 100)
_, readErr = port.ReadContext(context.Background(), buf)
close(done)
}()
time.Sleep(time.Millisecond)
select {
case <-done:
require.NoError(t, readErr)
require.Fail(t, "expected reading to be in-progress")
default:
}
port.Close()
time.Sleep(time.Millisecond)
select {
case <-done:
default:
require.Fail(t, "expected reading to be done")
}
var portErr *PortError
if !errors.As(readErr, &portErr) {
require.Fail(t, "expected read error to be a port error")
}
require.Equal(t, portErr.Code(), PortClosed)
}
func TestOpenReadCanceled(t *testing.T) {
// prevent port from being busy in other tests
defer time.Sleep(time.Millisecond)
port, err := openTestPort(t)
require.NoError(t, err)
defer port.Close()
readCtx, readCancel := context.WithCancel(context.Background())
done := make(chan struct{})
var readErr error
go func() {
buf := make([]byte, 100)
_, readErr = port.ReadContext(readCtx, buf)
close(done)
}()
time.Sleep(time.Millisecond)
select {
case <-done:
require.NoError(t, readErr)
require.Fail(t, "expected reading to be in-progress")
default:
}
readCancel()
time.Sleep(time.Millisecond)
select {
case <-done:
default:
require.Fail(t, "expected reading to be done")
}
var portErr *PortError
if !errors.As(readErr, &portErr) {
require.Fail(t, "expected read error to be a port error")
}
require.Equal(t, portErr.Code(), ReadCanceled)
}