1#!perl -T
2
3use lib "t";
4use TestTools;
5use Test::More tests => 11;
6use Device::USB;
7use strict;
8use warnings;
9
10my $usb = Device::USB->new();
11
12ok( defined $usb, "Object successfully created" );
13can_ok( $usb, "find_device_if" );
14
15ok( !defined $usb->find_device_if(
16            sub { 0xFFFF == $_->idVendor() && 0xFFFF == $_->idProduct() }
17        ),
18    "No device found"
19);
20
21eval { $usb->find_device_if() };
22like( $@, qr/Missing predicate/, "Requires a predicate." );
23
24eval { $usb->find_device_if( 1 ) };
25like( $@, qr/Predicate must be/, "Requires a code reference." );
26
27my $busses = $usb->list_busses();
28ok( defined $busses, "USB busses found" );
29
30my $found_device = TestTools::find_an_installed_device( 0, @{$busses} );
31
32SKIP:
33{
34    skip "No USB devices installed", 5 unless defined $found_device;
35
36    my $vendor = $found_device->idVendor();
37    my $product = $found_device->idProduct();
38
39    my $dev = $usb->find_device_if(
40        sub { $vendor == $_->idVendor() && $product == $_->idProduct() }
41    );
42
43    ok( defined $dev, "Device found." );
44    is_deeply( $dev, $found_device, "first device matches" );
45
46    my $count = @{$busses};
47    skip "Only one USB device installed", 3 if $count < 2;
48
49    $found_device = undef;
50    for(my $i = 1; $i < $count; ++$i)
51    {
52        my $dev = TestTools::find_an_installed_device( $i, @{$busses} );
53        next unless defined $dev;
54
55        # New vendor/product combination
56        if($vendor != $dev->idVendor() || $product != $dev->idProduct())
57        {
58            $found_device = $dev;
59            last;
60        }
61    }
62
63    skip "No accessible device found", 3 unless defined $found_device;
64    $vendor = $found_device->idVendor();
65    $product = $found_device->idProduct();
66
67    $dev = $usb->find_device_if(
68        sub { $vendor == $_->idVendor() && $product == $_->idProduct() }
69    );
70
71    ok( defined $dev, "Device found." );
72    is_deeply( $dev, $found_device, "second device matches" );
73
74    my $hub = $usb->find_device_if(
75        sub { Device::USB::CLASS_HUB == $_->bDeviceClass() }
76    );
77    ok( $hub && Device::USB::CLASS_HUB == $hub->bDeviceClass(),
78        "Hub found."
79    );
80}
81
82