]> git.mxchange.org Git - friendica.git/blob - tests/src/Util/CryptoTest.php
Using random_int directly
[friendica.git] / tests / src / Util / CryptoTest.php
1 <?php
2
3 // this is in the same namespace as Crypto for mocking 'rand' and 'random_init'
4 namespace Friendica\Util;
5
6 use PHPUnit\Framework\TestCase;
7
8 class CryptoTest extends TestCase
9 {
10         /**
11          * Replaces rand results with given mocks
12          *
13          */
14         private function assertRand($min, $max)
15         {
16                 global $phpMock;
17                 $phpMock['rand'] = function($mMin, $mMax) use ($min, $max) {
18                         $this->assertEquals($min, $mMin);
19                         $this->assertEquals($max, $mMax);
20                         return 1;
21                 };
22         }
23
24         /**
25          * Replaces random_int results with given mocks
26          *
27          */
28         private function assertRandomInt($min, $max)
29         {
30                 global $phpMock;
31                 $phpMock['random_int'] = function($mMin, $mMax) use ($min, $max) {
32                         $this->assertEquals($min, $mMin);
33                         $this->assertEquals($max, $mMax);
34                         return 1;
35                 };
36         }
37
38         public function testRandomDigitsRandomInt()
39         {
40                 $this->assertRandomInt(0, 9);
41
42                 $test = Crypto::randomDigits(1);
43                 $this->assertEquals(1, strlen($test));
44                 $this->assertEquals(1, $test);
45
46                 $test = Crypto::randomDigits(8);
47                 $this->assertEquals(8, strlen($test));
48                 $this->assertEquals(11111111, $test);
49         }
50 }
51
52 /**
53  * A workaround to replace the PHP native random_int() (>= 7.0) with a mocked function
54  *
55  * @return int
56  */
57 function random_int($min, $max)
58 {
59         global $phpMock;
60         if (isset($phpMock['random_int'])) {
61                 $result = call_user_func_array($phpMock['random_int'], func_get_args());
62                 return $result;
63         }
64 }