3 namespace Drupal\Tests\Component\Utility;
5 use Drupal\Component\Utility\Crypt;
6 use PHPUnit\Framework\TestCase;
9 * Tests random byte generation fallback exception situations.
13 * @runTestsInSeparateProcesses
15 * @coversDefaultClass \Drupal\Component\Utility\Crypt
17 class CryptRandomFallbackTest extends TestCase {
19 static protected $functionCalled = 0;
22 * Allows the test to confirm that the namespaced random_bytes() was called.
24 public static function functionCalled() {
25 static::$functionCalled++;
29 * Tests random byte generation using the fallback generator.
31 * If the call to random_bytes() throws an exception, Crypt::random_bytes()
32 * should still return a useful string of random bytes.
34 * @covers ::randomBytes
36 * @see \Drupal\Tests\Component\Utility\CryptTest::testRandomBytes()
38 public function testRandomBytesFallback() {
39 // This loop is a copy of
40 // \Drupal\Tests\Component\Utility\CryptTest::testRandomBytes().
41 for ($i = 0; $i < 10; $i++) {
42 $count = rand(10, 10000);
43 // Check that different values are being generated.
44 $this->assertNotEquals(Crypt::randomBytes($count), Crypt::randomBytes($count));
46 $this->assertEquals($count, strlen(Crypt::randomBytes($count)));
48 $this->assertEquals(30, static::$functionCalled, 'The namespaced function was called the expected number of times.');
53 namespace Drupal\Component\Utility;
55 use Drupal\Tests\Component\Utility\CryptRandomFallbackTest;
58 * Defines a function in same namespace as Drupal\Component\Utility\Crypt.
60 * Forces throwing an exception in this test environment because the function
61 * in the namespace is used in preference to the global function.
64 * Matches the global function definition.
68 function random_bytes($count) {
69 CryptRandomFallbackTest::functionCalled();
70 throw new \Exception($count);