summaryrefslogtreecommitdiff
path: root/t/op/srand.t
blob: 5321cde65682257c414c322aad5e187a32e9d1d4 (plain)
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
#!./perl -w

BEGIN {
    chdir "t" if -d "t";
    @INC = qw(. ../lib);
}

# Test srand.

use strict;

require "test.pl";
plan(tests => 10);

# Generate a load of random numbers.
# int() avoids possible floating point error.
sub mk_rand { map int rand 10000, 1..100; }


# Check that rand() is deterministic.
srand(1138);
my @first_run  = mk_rand;

srand(1138);
my @second_run = mk_rand;

ok( eq_array(\@first_run, \@second_run),  'srand(), same arg, same rands' );


# Check that different seeds provide different random numbers
srand(31337);
@first_run  = mk_rand;

srand(1138);
@second_run = mk_rand;

ok( !eq_array(\@first_run, \@second_run),
                                 'srand(), different arg, different rands' );


# Check that srand() isn't affected by $_
{   
    local $_ = 42;
    srand();
    @first_run  = mk_rand;

    srand(42);
    @second_run = mk_rand;

    ok( !eq_array(\@first_run, \@second_run),
                       'srand(), no arg, not affected by $_');
}

# This test checks whether Perl called srand for you.
@first_run  = `$^X -le "print int rand 100 for 1..100"`;
sleep(1); # in case our srand() is too time-dependent
@second_run = `$^X -le "print int rand 100 for 1..100"`;

ok( !eq_array(\@first_run, \@second_run), 'srand() called automatically');

# check srand's return value
my $seed = srand(1764);
is( $seed, 1764, "return value" );

$seed = srand(0);
ok( $seed, "true return value for srand(0)");
cmp_ok( $seed, '==', 0, "numeric 0 return value for srand(0)");

{
    my @warnings;
    my $b;
    {
	local $SIG{__WARN__} = sub {
	    push @warnings, "@_";
	    warn @_;
	};
	$b = $seed + 0;
    }
    is( $b, 0, "Quacks like a zero");
    is( "@warnings", "", "Does not warn");
}

# [perl #40605]
{
    use warnings;
    my $w = '';
    local $SIG{__WARN__} = sub { $w .= $_[0] };
    srand(2**100);
    like($w, qr/^Integer overflow in srand at /, "got a warning");
}