File: RandomBytesTest.php

package info (click to toggle)
php-random-compat 2.0.21-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 368 kB
  • sloc: php: 1,104; sh: 48; xml: 30; makefile: 4
file content (82 lines) | stat: -rw-r--r-- 2,374 bytes parent folder | download
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
<?php
class RandomBytesTest extends PHPUnit\Framework\TestCase
{
    public function testFuncExists()
    {
        $this->assertTrue(function_exists('random_bytes'));
    }
    
    public function testInvalidParams()
    {
        try {
            $bytes = random_bytes('good morning');
            $this->fail("random_bytes() should accept only an integer");
        } catch (TypeError $ex) {
            $this->assertTrue(true);
        } catch (Error $ex) {
            $this->assertTrue(true);
        } catch (Exception $ex) {
            $this->assertTrue(true);
        }
        
        try {
            $bytes = random_bytes(array(12));
            $this->fail("random_bytes() should accept only an integer");
        } catch (TypeError $ex) {
            $this->assertTrue(true);
        } catch (Error $ex) {
            $this->assertTrue(true);
        } catch (Exception $ex) {
            $this->assertTrue(true);
        }
        
        // This should succeed:
        $bytes = random_bytes('123456');
    }
    
    public function testOutput()
    {
        $bytes = array(
            random_bytes(12),
            random_bytes(64),
            random_bytes(64),
            PHP_VERSION_ID < 80100
                ? random_bytes(1.5)
                : random_bytes(1)
        );
        
        $this->assertTrue(
            strlen(bin2hex($bytes[0])) === 24
        );
        $this->assertTrue(
            strlen(bin2hex($bytes[3])) === 2
        );
        
        // This should never generate identical byte strings
        $this->assertFalse(
            $bytes[1] === $bytes[2]
        );
        
        try {
            $x = random_bytes(~PHP_INT_MAX - 1000000000);
            $this->fail("Integer overflow (~PHP_INT_MAX - 1000000000).");
        } catch (TypeError $ex) {
            $this->assertTrue(true);
        } catch (Error $ex) {
            $this->assertTrue(true);
        } catch (Exception $ex) {
            $this->assertTrue(true);
        }
        
        try {
            $x = random_bytes(PHP_INT_MAX + 1000000000);
            $this->fail("Requesting too many bytes should fail.");
        } catch (TypeError $ex) {
            $this->assertTrue(true);
        } catch (Error $ex) {
            $this->assertTrue(true);
        } catch (Exception $ex) {
            $this->assertTrue(true);
        }
    }
}