xref: /PHP-8.1/ext/gmp/tests/gmp_random_range.phpt (revision e9f783fc)
1--TEST--
2gmp_random_range() basic tests
3--EXTENSIONS--
4gmp
5--FILE--
6<?php
7
8$minusTen = gmp_init(-10);
9$plusTen = gmp_init(10);
10$zero = gmp_init(0);
11
12try {
13    var_dump(gmp_random_range(10, -10));
14} catch (\ValueError $e) {
15    echo $e->getMessage() . \PHP_EOL;
16}
17
18try {
19    var_dump(gmp_random_range($plusTen, $minusTen));
20} catch (\ValueError $e) {
21    echo $e->getMessage() . \PHP_EOL;
22}
23try {
24    var_dump(gmp_random_range($plusTen, $zero));
25} catch (\ValueError $e) {
26    echo $e->getMessage() . \PHP_EOL;
27}
28
29// If these error the test fails.
30gmp_random_range(0, 10);
31gmp_random_range(1, 10);
32gmp_random_range(-1, 10);
33gmp_random_range(-10, 0);
34gmp_random_range(-10, -1);
35
36gmp_random_range(0, $plusTen);
37gmp_random_range(1, $plusTen);
38gmp_random_range(-1, $plusTen);
39
40gmp_random_range($zero, $plusTen);
41gmp_random_range($minusTen, $plusTen);
42
43// 0.5 seconds to make sure the numbers stay in range
44$start = microtime(true);
45while (1) {
46    for ($i = 0; $i < 5000; $i++) {
47        $result = gmp_random_range(0, 1000);
48        if ($result < 0 || $result > 1000) {
49            print "RANGE VIOLATION 1\n";
50            var_dump($result);
51            break 2;
52        }
53
54        $result = gmp_random_range(-1000, 0);
55        if ($result < -1000 || $result > 0) {
56            print "RANGE VIOLATION 2\n";
57            var_dump($result);
58            break 2;
59        }
60
61        $result = gmp_random_range(-500, 500);
62        if ($result < -500 || $result > 500) {
63            print "RANGE VIOLATION 3\n";
64            var_dump($result);
65            break 2;
66        }
67    }
68
69    if (microtime(true) - $start > 0.5) {
70        break;
71    }
72}
73
74echo "Done\n";
75?>
76--EXPECT--
77gmp_random_range(): Argument #1 ($min) must be less than argument #2 ($maximum)
78gmp_random_range(): Argument #1 ($min) must be less than argument #2 ($maximum)
79gmp_random_range(): Argument #1 ($min) must be less than argument #2 ($maximum)
80Done
81