1#!perl -T
2use strict;
3use Test::More;
4use Net::Pcap;
5use lib 't';
6use Utils;
7
8my $total = 1;  # number of packets to process
9
10plan skip_all => "must be run as root" unless is_allowed_to_use_pcap();
11plan skip_all => "no network device available" unless find_network_device();
12plan tests => $total * 11 + 5;
13
14my $has_test_exception = eval "use Test::Exception; 1";
15
16my($dev,$pcap,$dumper,$dump_file,$err) = ('','','','');
17
18# Find a device and open it
19$dev = find_network_device();
20$pcap = Net::Pcap::open_live($dev, 1024, 1, 100, \$err);
21
22# Testing error messages
23SKIP: {
24    skip "Test::Exception not available", 2 unless $has_test_exception;
25
26    # dispatch() errors
27    throws_ok(sub {
28        Net::Pcap::dispatch()
29    }, '/^Usage: Net::Pcap::dispatch\(p, cnt, callback, user\)/',
30       "calling dispatch() with no argument");
31
32    throws_ok(sub {
33        Net::Pcap::dispatch(0, 0, 0, 0)
34    }, '/^p is not of type pcap_tPtr/',
35       "calling dispatch() with incorrect argument type");
36
37}
38
39my $user_text = "Net::Pcap test suite";
40my $count = 0;
41
42sub process_packet {
43    my($user_data, $header, $packet) = @_;
44    my %stats = ();
45
46    eval { Net::Pcap::stats($pcap, \%stats) };
47    is(   $@,   '', "stats()" );
48    is( keys %stats, 3, " - %stats has 3 elements" );
49
50    for my $field (qw(ps_recv ps_drop ps_ifdrop)) {
51        ok( exists $stats{$field}, "    - field '$field' is present" );
52        ok( defined $stats{$field}, "    - field '$field' is defined" );
53        like( $stats{$field}, '/^\d+$/', "    - field '$field' is a number" );
54    }
55
56    $count++;
57}
58
59my $retval = 0;
60eval { $retval = Net::Pcap::dispatch($pcap, $total, \&process_packet, $user_text) };
61is(   $@,   '', "dispatch()" );
62
63SKIP: {
64    skip "not enought packets or other unknown problem",
65      11 * ($total - $count) + 2 if $count < $total;
66    is( $count, $total, "checking the number of processed packets" );
67    is( $retval, $count, "checking return value" );
68}
69
70Net::Pcap::close($pcap);
71
72