-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdevice_test.go
More file actions
355 lines (306 loc) · 9.12 KB
/
Copy pathdevice_test.go
File metadata and controls
355 lines (306 loc) · 9.12 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright (c) 2015-2026 The usbtmc developers. All rights reserved.
// Project site: https://github.com/gotmc/usbtmc
// Use of this source code is governed by a MIT-style license that
// can be found in the LICENSE.txt file for the project.
package usbtmc
import (
"context"
"encoding/binary"
"errors"
"testing"
)
// mockUSBDevice records writes and replays reads for testing.
type mockUSBDevice struct {
writes [][]byte // captured raw writes
reads [][]byte // queued responses to return from Read
readN int // index into reads
closed bool
}
func (m *mockUSBDevice) Write(p []byte) (int, error) {
return m.WriteContext(context.Background(), p)
}
func (m *mockUSBDevice) WriteContext(_ context.Context, p []byte) (int, error) {
cp := make([]byte, len(p))
copy(cp, p)
m.writes = append(m.writes, cp)
return len(p), nil
}
func (m *mockUSBDevice) WriteString(s string) (int, error) {
return m.Write([]byte(s))
}
func (m *mockUSBDevice) Read(p []byte) (int, error) {
return m.ReadContext(context.Background(), p)
}
func (m *mockUSBDevice) ReadContext(_ context.Context, p []byte) (int, error) {
if m.readN >= len(m.reads) {
return 0, errors.New("mock: no more reads queued")
}
data := m.reads[m.readN]
m.readN++
n := copy(p, data)
return n, nil
}
func (m *mockUSBDevice) Close() error {
m.closed = true
return nil
}
func (m *mockUSBDevice) String() string {
return "mock"
}
// buildDevDepMsgInResponse builds a USBTMC DEV_DEP_MSG_IN response header
// with the given bTag and payload.
func buildDevDepMsgInResponse(bTag byte, payload []byte) []byte {
hdr := make([]byte, usbtmcHeaderLen)
hdr[0] = byte(devDepMsgIn)
hdr[1] = bTag
hdr[2] = invertbTag(bTag)
hdr[3] = 0x00
binary.LittleEndian.PutUint32(hdr[4:8], uint32(len(payload))) //nolint:gosec
hdr[8] = 0x01 // EOM
resp := append(hdr, payload...)
// Pad to 4-byte alignment.
if m := len(resp) % 4; m != 0 {
resp = append(resp, make([]byte, 4-m)...)
}
return resp
}
func newTestDevice(mock *mockUSBDevice) *Device {
return &Device{
usbDevice: mock,
bTag: 0,
termChar: '\n',
termCharEnabled: true,
}
}
func TestWriteSingleChunk(t *testing.T) {
mock := &mockUSBDevice{}
dev := newTestDevice(mock)
data := []byte("*IDN?\n")
n, err := dev.Write(data)
if err != nil {
t.Fatalf("Write returned error: %v", err)
}
if n != len(data) {
t.Errorf("Write returned n=%d, want %d", n, len(data))
}
if len(mock.writes) != 1 {
t.Fatalf("expected 1 USB write, got %d", len(mock.writes))
}
// Verify header: msgID=devDepMsgOut(1), bTag=1, transferSize=6, EOM=1.
w := mock.writes[0]
if w[0] != byte(devDepMsgOut) {
t.Errorf("msgID = %d, want %d", w[0], devDepMsgOut)
}
if w[1] != 1 {
t.Errorf("bTag = %d, want 1", w[1])
}
transferSize := binary.LittleEndian.Uint32(w[4:8])
if transferSize != uint32(len(data)) { //nolint:gosec
t.Errorf("transferSize = %d, want %d", transferSize, len(data))
}
if w[8] != 0x01 {
t.Errorf("EOM = %d, want 1", w[8])
}
// Verify payload follows header.
payload := w[bulkOutHeaderSize : bulkOutHeaderSize+len(data)]
for i, b := range payload {
if b != data[i] {
t.Errorf("payload[%d] = %x, want %x", i, b, data[i])
}
}
}
func TestWriteMultiChunk(t *testing.T) {
mock := &mockUSBDevice{}
dev := newTestDevice(mock)
// Create data larger than maxTransferSize - bulkOutHeaderSize (500 bytes).
data := make([]byte, 600)
for i := range data {
data[i] = byte(i % 256)
}
n, err := dev.Write(data)
if err != nil {
t.Fatalf("Write returned error: %v", err)
}
if n != len(data) {
t.Errorf("Write returned n=%d, want %d", n, len(data))
}
if len(mock.writes) != 2 {
t.Fatalf("expected 2 USB writes, got %d", len(mock.writes))
}
// First chunk: EOM should be 0.
if mock.writes[0][8] != 0x00 {
t.Errorf("first chunk EOM = %d, want 0", mock.writes[0][8])
}
// Second chunk: EOM should be 1.
if mock.writes[1][8] != 0x01 {
t.Errorf("second chunk EOM = %d, want 1", mock.writes[1][8])
}
}
func TestReadSingleTransfer(t *testing.T) {
mock := &mockUSBDevice{}
dev := newTestDevice(mock)
payload := []byte("Keysight Technologies\n")
// The first bTag after 0 will be 1.
resp := buildDevDepMsgInResponse(1, payload)
mock.reads = [][]byte{resp}
buf := make([]byte, 100)
n, err := dev.Read(buf)
if err != nil {
t.Fatalf("Read returned error: %v", err)
}
if n != len(payload) {
t.Errorf("Read returned n=%d, want %d", n, len(payload))
}
if string(buf[:n]) != string(payload) {
t.Errorf("Read data = %q, want %q", buf[:n], payload)
}
// Verify the request header was sent (requestDevDepMsgIn).
if len(mock.writes) != 1 {
t.Fatalf("expected 1 write for request header, got %d", len(mock.writes))
}
if mock.writes[0][0] != byte(requestDevDepMsgIn) {
t.Errorf("request msgID = %d, want %d", mock.writes[0][0], requestDevDepMsgIn)
}
}
func TestReadRawNoTermChar(t *testing.T) {
mock := &mockUSBDevice{}
dev := newTestDevice(mock)
payload := []byte{0x01, 0x02, 0x03, 0x04}
resp := buildDevDepMsgInResponse(1, payload)
mock.reads = [][]byte{resp}
buf := make([]byte, 100)
n, err := dev.ReadRaw(buf)
if err != nil {
t.Fatalf("ReadRaw returned error: %v", err)
}
if n != len(payload) {
t.Errorf("ReadRaw returned n=%d, want %d", n, len(payload))
}
// Verify termCharEnabled is NOT set in the request header (bit 1 of byte 8).
reqHeader := mock.writes[0]
if reqHeader[8]&0x02 != 0 {
t.Error("ReadRaw request has termCharEnabled set, want unset")
}
}
func TestCommand(t *testing.T) {
mock := &mockUSBDevice{}
dev := newTestDevice(mock)
err := dev.Command(context.Background(), "FREQ %d", 1000)
if err != nil {
t.Fatalf("Command returned error: %v", err)
}
if len(mock.writes) != 1 {
t.Fatalf("expected 1 USB write, got %d", len(mock.writes))
}
// Extract payload from the write (skip 12-byte header).
w := mock.writes[0]
transferSize := binary.LittleEndian.Uint32(w[4:8])
payload := string(w[bulkOutHeaderSize : bulkOutHeaderSize+transferSize])
expected := "FREQ 1000\n"
if payload != expected {
t.Errorf("Command payload = %q, want %q", payload, expected)
}
}
func TestQuery(t *testing.T) {
mock := &mockUSBDevice{}
dev := newTestDevice(mock)
respPayload := []byte("1.00000E+03\n")
// Query does a Write (bTag becomes 1), then a Read (bTag becomes 2).
resp := buildDevDepMsgInResponse(2, respPayload)
mock.reads = [][]byte{resp}
result, err := dev.Query(context.Background(), "*IDN?")
if err != nil {
t.Fatalf("Query returned error: %v", err)
}
if result != string(respPayload) {
t.Errorf("Query result = %q, want %q", result, respPayload)
}
// Should have 2 writes: one for Command, one for Read request header.
if len(mock.writes) != 2 {
t.Fatalf("expected 2 USB writes, got %d", len(mock.writes))
}
}
func TestWriteBinaryCancellation(t *testing.T) {
mock := &mockUSBDevice{}
dev := newTestDevice(mock)
ctx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately.
_, err := dev.WriteBinary(ctx, []byte("data"))
if err == nil {
t.Fatal("WriteBinary with cancelled context should return error")
}
if !errors.Is(err, context.Canceled) {
t.Errorf("error = %v, want context.Canceled", err)
}
if len(mock.writes) != 0 {
t.Errorf("expected 0 USB writes, got %d", len(mock.writes))
}
}
func TestReadBinaryCancellation(t *testing.T) {
mock := &mockUSBDevice{}
dev := newTestDevice(mock)
ctx, cancel := context.WithCancel(context.Background())
cancel()
buf := make([]byte, 100)
_, err := dev.ReadBinary(ctx, buf)
if err == nil {
t.Fatal("ReadBinary with cancelled context should return error")
}
if !errors.Is(err, context.Canceled) {
t.Errorf("error = %v, want context.Canceled", err)
}
}
func TestReadBTagMismatch(t *testing.T) {
mock := &mockUSBDevice{}
dev := newTestDevice(mock)
// Build response with wrong bTag (99 instead of expected 1).
payload := []byte("data")
resp := buildDevDepMsgInResponse(99, payload)
mock.reads = [][]byte{resp}
buf := make([]byte, 100)
_, err := dev.Read(buf)
if err == nil {
t.Fatal("Read with mismatched bTag should return error")
}
if !contains(err.Error(), "bTag mismatch") {
t.Errorf("error = %v, want bTag mismatch error", err)
}
}
func TestReadWrongMsgID(t *testing.T) {
mock := &mockUSBDevice{}
dev := newTestDevice(mock)
// Build a response with wrong msgID (devDepMsgOut instead of devDepMsgIn).
resp := buildDevDepMsgInResponse(1, []byte("data"))
resp[0] = byte(devDepMsgOut)
mock.reads = [][]byte{resp}
buf := make([]byte, 100)
_, err := dev.Read(buf)
if err == nil {
t.Fatal("Read with wrong MsgID should return error")
}
if !contains(err.Error(), "unexpected MsgID") {
t.Errorf("error = %v, want unexpected MsgID error", err)
}
}
func TestClose(t *testing.T) {
mock := &mockUSBDevice{}
dev := newTestDevice(mock)
err := dev.Close()
if err != nil {
t.Fatalf("Close returned error: %v", err)
}
if !mock.closed {
t.Error("expected underlying USB device to be closed")
}
}
func contains(s, substr string) bool {
return len(s) >= len(substr) && searchString(s, substr)
}
func searchString(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}