76e3076f0f3efe10d7dee6c61dcf3421ac94bfa3
[friendica.git/.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 random_int results with given mocks
12          *
13          */
14         private function assertRandomInt($min, $max)
15         {
16                 global $phpMock;
17                 $phpMock['random_int'] = function($mMin, $mMax) use ($min, $max) {
18                         $this->assertEquals($min, $mMin);
19                         $this->assertEquals($max, $mMax);
20                         return 1;
21                 };
22         }
23
24         public function testRandomDigitsRandomInt()
25         {
26                 $this->assertRandomInt(0, 9);
27
28                 $test = Crypto::randomDigits(1);
29                 $this->assertEquals(1, strlen($test));
30                 $this->assertEquals(1, $test);
31
32                 $test = Crypto::randomDigits(8);
33                 $this->assertEquals(8, strlen($test));
34                 $this->assertEquals(11111111, $test);
35         }
36 }
37
38 /**
39  * A workaround to replace the PHP native random_int() (>= 7.0) with a mocked function
40  *
41  * @return int
42  */
43 function random_int($min, $max)
44 {
45         global $phpMock;
46         if (isset($phpMock['random_int'])) {
47                 $result = call_user_func_array($phpMock['random_int'], func_get_args());
48                 return $result;
49         }
50 }