comparison core/tests/Drupal/Tests/Component/Utility/CryptRandomFallbackTest.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children af1871eacc83
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\Tests\Component\Utility;
4
5 use Drupal\Component\Utility\Crypt;
6 use PHPUnit\Framework\TestCase;
7
8 /**
9 * Tests random byte generation fallback exception situations.
10 *
11 * @group Utility
12 *
13 * @runTestsInSeparateProcesses
14 *
15 * @coversDefaultClass \Drupal\Component\Utility\Crypt
16 */
17 class CryptRandomFallbackTest extends TestCase {
18
19 static protected $functionCalled = 0;
20
21 /**
22 * Allows the test to confirm that the namespaced random_bytes() was called.
23 */
24 public static function functionCalled() {
25 static::$functionCalled++;
26 }
27
28 /**
29 * Tests random byte generation using the fallback generator.
30 *
31 * If the call to random_bytes() throws an exception, Crypt::random_bytes()
32 * should still return a useful string of random bytes.
33 *
34 * @covers ::randomBytes
35 *
36 * @see \Drupal\Tests\Component\Utility\CryptTest::testRandomBytes()
37 */
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));
45 // Check the length.
46 $this->assertEquals($count, strlen(Crypt::randomBytes($count)));
47 }
48 $this->assertEquals(30, static::$functionCalled, 'The namespaced function was called the expected number of times.');
49 }
50
51 }
52
53 namespace Drupal\Component\Utility;
54
55 use Drupal\Tests\Component\Utility\CryptRandomFallbackTest;
56
57 /**
58 * Defines a function in same namespace as Drupal\Component\Utility\Crypt.
59 *
60 * Forces throwing an exception in this test environment because the function
61 * in the namespace is used in preference to the global function.
62 *
63 * @param int $count
64 * Matches the global function definition.
65 *
66 * @throws \Exception
67 */
68 function random_bytes($count) {
69 CryptRandomFallbackTest::functionCalled();
70 throw new \Exception($count);
71 }