3 // this is in the same namespace as Install for mocking 'rand' and 'random_init'
4 namespace Friendica\Util;
6 use PHPUnit\Framework\TestCase;
8 class CryptoTest extends TestCase
11 * Replaces function_exists results with given mocks
13 * @param array $functions a list from function names and their result
15 private function setFunctions($functions)
18 $phpMock['function_exists'] = function($function) use ($functions) {
19 foreach ($functions as $name => $value) {
20 if ($function == $name) {
24 return '__phpunit_continue__';
29 * Replaces rand results with given mocks
32 private function assertRand($min, $max)
35 $phpMock['rand'] = function($mMin, $mMax) use ($min, $max) {
36 $this->assertEquals($min, $mMin);
37 $this->assertEquals($max, $mMax);
43 * Replaces rand results with given mocks
46 private function assertRandomInt($min, $max)
49 $phpMock['random_int'] = function($mMin, $mMax) use ($min, $max) {
50 $this->assertEquals($min, $mMin);
51 $this->assertEquals($max, $mMax);
56 public function testRandomDigitsRand()
58 $this->setFunctions(['random_int' => false]);
59 $this->assertRand(0, 9);
61 $test = Crypto::randomDigits(1);
62 $this->assertEquals(1, strlen($test));
63 $this->assertEquals(1, $test);
65 $test = Crypto::randomDigits(8);
66 $this->assertEquals(8, strlen($test));
67 $this->assertEquals(11111111, $test);
71 public function testRandomDigitsRandomInt()
73 $this->setFunctions(['random_int' => true]);
74 $this->assertRandomInt(0, 9);
76 $test = Crypto::randomDigits(1);
77 $this->assertEquals(1, strlen($test));
78 $this->assertEquals(1, $test);
80 $test = Crypto::randomDigits(8);
81 $this->assertEquals(8, strlen($test));
82 $this->assertEquals(11111111, $test);
87 * A workaround to replace the PHP native function_exists() with a mocked function
89 * @param string $function_name the Name of the function
91 * @return bool true or false
93 function function_exists($function_name)
96 if (isset($phpMock['function_exists'])) {
97 $result = call_user_func_array($phpMock['function_exists'], func_get_args());
98 if ($result !== '__phpunit_continue__') {
102 return call_user_func_array('\function_exists', func_get_args());
106 * A workaround to replace the PHP native rand() (< 7.0) with a mocked function
110 function rand($min, $max)
113 if (isset($phpMock['rand'])) {
114 $result = call_user_func_array($phpMock['rand'], func_get_args());
120 * A workaround to replace the PHP native random_int() (>= 7.0) with a mocked function
124 function random_int($min, $max)
127 if (isset($phpMock['random_int'])) {
128 $result = call_user_func_array($phpMock['random_int'], func_get_args());