Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 namespace Drupal\Tests\Component\Utility;
|
Chris@0
|
4
|
Chris@0
|
5 use Drupal\Component\Utility\Crypt;
|
Chris@0
|
6 use PHPUnit\Framework\TestCase;
|
Chris@0
|
7
|
Chris@0
|
8 /**
|
Chris@0
|
9 * Tests random byte generation fallback exception situations.
|
Chris@0
|
10 *
|
Chris@0
|
11 * @group Utility
|
Chris@0
|
12 *
|
Chris@0
|
13 * @runTestsInSeparateProcesses
|
Chris@0
|
14 *
|
Chris@0
|
15 * @coversDefaultClass \Drupal\Component\Utility\Crypt
|
Chris@0
|
16 */
|
Chris@0
|
17 class CryptRandomFallbackTest extends TestCase {
|
Chris@0
|
18
|
Chris@18
|
19 protected static $functionCalled = 0;
|
Chris@0
|
20
|
Chris@0
|
21 /**
|
Chris@0
|
22 * Allows the test to confirm that the namespaced random_bytes() was called.
|
Chris@0
|
23 */
|
Chris@0
|
24 public static function functionCalled() {
|
Chris@0
|
25 static::$functionCalled++;
|
Chris@0
|
26 }
|
Chris@0
|
27
|
Chris@0
|
28 /**
|
Chris@0
|
29 * Tests random byte generation using the fallback generator.
|
Chris@0
|
30 *
|
Chris@0
|
31 * If the call to random_bytes() throws an exception, Crypt::random_bytes()
|
Chris@0
|
32 * should still return a useful string of random bytes.
|
Chris@0
|
33 *
|
Chris@0
|
34 * @covers ::randomBytes
|
Chris@0
|
35 *
|
Chris@0
|
36 * @see \Drupal\Tests\Component\Utility\CryptTest::testRandomBytes()
|
Chris@0
|
37 */
|
Chris@0
|
38 public function testRandomBytesFallback() {
|
Chris@0
|
39 // This loop is a copy of
|
Chris@0
|
40 // \Drupal\Tests\Component\Utility\CryptTest::testRandomBytes().
|
Chris@0
|
41 for ($i = 0; $i < 10; $i++) {
|
Chris@0
|
42 $count = rand(10, 10000);
|
Chris@0
|
43 // Check that different values are being generated.
|
Chris@0
|
44 $this->assertNotEquals(Crypt::randomBytes($count), Crypt::randomBytes($count));
|
Chris@0
|
45 // Check the length.
|
Chris@0
|
46 $this->assertEquals($count, strlen(Crypt::randomBytes($count)));
|
Chris@0
|
47 }
|
Chris@0
|
48 $this->assertEquals(30, static::$functionCalled, 'The namespaced function was called the expected number of times.');
|
Chris@0
|
49 }
|
Chris@0
|
50
|
Chris@0
|
51 }
|
Chris@0
|
52
|
Chris@0
|
53 namespace Drupal\Component\Utility;
|
Chris@0
|
54
|
Chris@0
|
55 use Drupal\Tests\Component\Utility\CryptRandomFallbackTest;
|
Chris@0
|
56
|
Chris@0
|
57 /**
|
Chris@0
|
58 * Defines a function in same namespace as Drupal\Component\Utility\Crypt.
|
Chris@0
|
59 *
|
Chris@0
|
60 * Forces throwing an exception in this test environment because the function
|
Chris@0
|
61 * in the namespace is used in preference to the global function.
|
Chris@0
|
62 *
|
Chris@0
|
63 * @param int $count
|
Chris@0
|
64 * Matches the global function definition.
|
Chris@0
|
65 *
|
Chris@0
|
66 * @throws \Exception
|
Chris@0
|
67 */
|
Chris@0
|
68 function random_bytes($count) {
|
Chris@0
|
69 CryptRandomFallbackTest::functionCalled();
|
Chris@0
|
70 throw new \Exception($count);
|
Chris@0
|
71 }
|