1# Tests for /dev/random
2
3use strict;
4use warnings;
5
6use Test::More;
7
8my @WARN;
9BEGIN {
10    # Warning signal handler
11    $SIG{__WARN__} = sub { push(@WARN, @_); };
12}
13
14if (-e '/dev/random') {
15    my $FH;
16    if (open($FH, '<', '/dev/random')) {
17        binmode($FH);
18        my $data;
19        my $cnt = read($FH, $data, 8);
20        if (! defined($cnt)) {
21            plan skip_all => "Couldn't read from /dev/random: $!";
22        } elsif ($cnt == 8) {
23            plan tests => 92;
24        } else {
25            plan skip_all => "/dev/random exhausted ($cnt of 8 bytes)";
26        }
27        close($FH);
28    } else {
29        plan skip_all => "/dev/random not usable: $!";
30    }
31} else {
32    plan skip_all => '/dev/random not available';
33}
34
35use_ok('Math::Random::MT::Auto', qw(rand irand), '/dev/random');
36can_ok('main', qw(rand irand));
37
38# Check for warnings
39if (grep { /exhausted/ } @WARN) {
40    diag('/dev/random exhausted');
41    undef(@WARN);
42}
43if (grep { /unavailable/ } @WARN) {
44    diag('/dev/random unavailable');
45    undef(@WARN);
46}
47if (grep { /Failure reading/ } @WARN) {
48    diag('Seed warning ignored: ' . join(' | ', @WARN));
49    undef(@WARN);
50}
51if (! ok(! @WARN, 'Acquired seed data')) {
52    diag('Seed warnings: ' . join(' | ', @WARN));
53}
54undef(@WARN);
55
56my ($rn, @rn);
57
58# Test rand()
59eval { $rn = rand(); };
60ok(! $@,                    'rand() died: ' . $@);
61ok(defined($rn),            'Got a random number');
62ok(Scalar::Util::looks_like_number($rn),  'Is a number: ' . $rn);
63ok($rn >= 0.0 && $rn < 1.0, 'In range: ' . $rn);
64
65# Test several values from irand()
66for my $ii (0 .. 9) {
67    eval { $rn[$ii] = irand(); };
68    ok(! $@,                        'irand() died: ' . $@);
69    ok(defined($rn[$ii]),           'Got a random number');
70    ok(Scalar::Util::looks_like_number($rn[$ii]), 'Is a number: ' . $rn[$ii]);
71    ok(int($rn[$ii]) == $rn[$ii],   'Integer: ' . $rn[$ii]);
72    for my $jj (0 .. $ii-1) {
73        ok($rn[$jj] != $rn[$ii],    'Randomized');
74    }
75}
76
77exit(0);
78
79# EOF
80