From d392ad305d6ffd4da7407a45eed55e7c0813f3ac Mon Sep 17 00:00:00 2001 From: Sebastian Zagrodzki Date: Fri, 10 Mar 2017 07:38:54 -0500 Subject: [PATCH] Tests for OpenVidPid --- usb/usb.go | 7 ++++--- usb/usb_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/usb/usb.go b/usb/usb.go index bf36902..12924f3 100644 --- a/usb/usb.go +++ b/usb/usb.go @@ -80,12 +80,13 @@ func (c *Context) ListDevices(each func(desc *Descriptor) bool) ([]*Device, erro // it will return a non-nil device and non-nil error. A Device.Close() must // be called to release the device if the returned device wasn't nil. func (c *Context) OpenDeviceWithVidPid(vid, pid int) (*Device, error) { - dev * Device - devs, err := ListDevices(func(desc *Descriptor) { - if dev != nil { + var found bool + devs, err := c.ListDevices(func(desc *Descriptor) bool { + if found { return false } if desc.Vendor == ID(vid) && desc.Product == ID(pid) { + found = true return true } return false diff --git a/usb/usb_test.go b/usb/usb_test.go index 0485d7c..5245119 100644 --- a/usb/usb_test.go +++ b/usb/usb_test.go @@ -53,3 +53,32 @@ func TestListDevices(t *testing.T) { } } } + +func TestOpenDeviceWithVidPid(t *testing.T) { + orig := libusb + defer func() { libusb = orig }() + libusb = newFakeLibusb() + + for _, d := range []struct { + vid, pid int + exists bool + }{ + {0x7777, 0x0003, false}, + {0x8888, 0x0001, false}, + {0x8888, 0x0002, true}, + {0x9999, 0x0001, true}, + {0x9999, 0x0002, false}, + } { + c := NewContext() + dev, err := c.OpenDeviceWithVidPid(d.vid, d.pid) + if (dev != nil) != d.exists { + t.Errorf("OpenDeviceWithVidPid(%s/%s): device != nil is %v, want %v", ID(d.vid), ID(d.pid), dev != nil, d.exists) + } + if err != nil { + t.Errorf("OpenDeviceWithVidPid(%s/%s): got error %v, want nil", ID(d.vid), ID(d.pid), err) + } + if dev != nil { + dev.Close() + } + } +}