File: Util.pm

package info (click to toggle)
libnet-proxy-perl 0.12-5
  • links: PTS
  • area: main
  • in suites: squeeze, wheezy
  • size: 304 kB
  • ctags: 66
  • sloc: perl: 777; sh: 84; makefile: 44
file content (90 lines) | stat: -rw-r--r-- 1,936 bytes parent folder | download | duplicates (5)
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
use strict;
use warnings;
use IO::Socket::INET;

# return sockets connected to free ports
# we can use sockport() to learn the port values
# and close() to close the socket just before reopening it
sub find_free_ports {
    my $n = shift;
    my @socks;

    for ( 1 .. $n ) {
        my $sock = listen_on_port(0);
        if ($sock) {
            push @socks, $sock;
        }
    }
    my @ports = map { $_->sockport() } @socks;
    diag "ports: @ports";

    # close the sockets and return the ports
    $_->close() for @socks;
    return @ports;
}

# return a socket connected to port $port on localhost
sub connect_to_port {
    my ($port, %opts) = @_;
    return IO::Socket::INET->new(
        PeerAddr => 'localhost',
        PeerPort => $port,
        Proto    => 'tcp',
        %opts
    );
}

# return a socket listening on $port on localhost
sub listen_on_port {
    my ($port) = @_;
    return IO::Socket::INET->new(
        Listen    => 1,
        LocalAddr => 'localhost',
        LocalPort => $port,
        Proto     => 'tcp',
    );
}

# compute a seed and show it
use POSIX qw( INT_MAX );

sub init_rand {
    my $seed = @_ ? $_[0] : int rand INT_MAX;
    diag "Random seed $seed";
    srand $seed;
}

# randomly exchange (or not) a pair
sub random_swap {
    my ( $first, $second ) = @_;
    return rand > 0.5 ? ( $first, $second ) : ( $second, $first );
}

# skip but fail
# extends Test::More
use Test::Builder;
sub skip_fail {
    my ($why, $how_many) = @_;
    my $Test = Test::Builder->new();
    for( 1 .. $how_many ) {
        $Test->ok( 0, $why );
    }
    no warnings;
    last SKIP;
}

use IO::Select;
use Test::More;
sub is_closed {
    my ($sock, $name) = @_;
    $name ||= "$sock";
    my $select = IO::Select->new( $sock );
    my @read   =  $select->can_read();
    if( @read ) {
        my $buf;
        my $read = $read[0]->sysread( $buf, 4096 );
        is( $read, 0, "$name closed" );
    }
}

1;