๐Ÿ“ฆ karalabe / usb

๐Ÿ“„ usb_test.go ยท 87 lines
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// usb - Self contained USB and HID library for Go
// Copyright 2017 The library Authors
//
// This library is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option) any
// later version.
//
// The library is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
// A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along
// with the library. If not, see <http://www.gnu.org/licenses/>.

package usb

import (
	"os"
	"runtime"
	"sync"
	"testing"
)

// Tests that HID enumeration can be called concurrently from multiple threads.
func TestThreadedEnumerateHid(t *testing.T) {
	var pend sync.WaitGroup
	for i := 0; i < 8; i++ {
		pend.Add(1)

		go func(index int) {
			defer pend.Done()
			for j := 0; j < 512; j++ {
				if _, err := EnumerateHid(uint16(index), 0); err != nil {
					t.Errorf("thread %d, iter %d: failed to enumerate: %v", index, j, err)
				}
			}
		}(i)
	}
	pend.Wait()
}

// Tests that RAW enumeration can be called concurrently from multiple threads.
func TestThreadedEnumerateRaw(t *testing.T) {
	// Travis does not have usbfs enabled in the Linux kernel
	if os.Getenv("TRAVIS") != "" && runtime.GOOS == "linux" {
		t.Skip("Linux on Travis doesn't have usbfs, skipping test")
	}
	// Yay, we can actually test this
	var pend sync.WaitGroup
	for i := 0; i < 8; i++ {
		pend.Add(1)

		go func(index int) {
			defer pend.Done()
			for j := 0; j < 512; j++ {
				if _, err := EnumerateRaw(uint16(index), 0); err != nil {
					t.Errorf("thread %d, iter %d: failed to enumerate: %v", index, j, err)
				}
			}
		}(i)
	}
	pend.Wait()
}

// Tests that generic enumeration can be called concurrently from multiple threads.
func TestThreadedEnumerate(t *testing.T) {
	// Travis does not have usbfs enabled in the Linux kernel
	if os.Getenv("TRAVIS") != "" && runtime.GOOS == "linux" {
		t.Skip("Linux on Travis doesn't have usbfs, skipping test")
	}
	var pend sync.WaitGroup
	for i := 0; i < 8; i++ {
		pend.Add(1)

		go func(index int) {
			defer pend.Done()
			for j := 0; j < 512; j++ {
				if _, err := Enumerate(uint16(index), 0); err != nil {
					t.Errorf("thread %d, iter %d: failed to enumerate: %v", index, j, err)
				}
			}
		}(i)
	}
	pend.Wait()
}