1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace { |
4
|
|
|
$mockRandomPseudoBytes = false; |
5
|
|
|
} |
6
|
|
|
|
7
|
|
|
namespace Majora\Component\OAuth\Generator { |
8
|
|
|
/** |
9
|
|
|
* override global method to tests if function cannot get a strong hash. |
10
|
|
|
*/ |
11
|
|
|
function openssl_random_pseudo_bytes($length, &$strong) |
12
|
|
|
{ |
13
|
|
|
global $mockRandomPseudoBytes; |
|
|
|
|
14
|
|
|
if (isset($mockRandomPseudoBytes) && $mockRandomPseudoBytes === true) { |
15
|
|
|
$strong = false; |
16
|
|
|
|
17
|
|
|
return 12345; |
18
|
|
|
} else { |
19
|
|
|
return \openssl_random_pseudo_bytes($length, $strong); |
20
|
|
|
} |
21
|
|
|
} |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
namespace Majora\Component\OAuth\Tests\Generator { |
25
|
|
|
|
26
|
|
|
use Majora\Component\OAuth\Generator\RandomTokenGenerator; |
|
|
|
|
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Unit test class for Majora\Component\OAuth\Generator\RandomTokenGenerator. |
30
|
|
|
*/ |
31
|
|
|
class RandomTokenGeneratorTest extends \PHPUnit_Framework_TestCase |
32
|
|
|
{ |
33
|
|
|
/** |
34
|
|
|
* SetUp method overriden to reset global mock boolean. |
35
|
|
|
*/ |
36
|
|
|
public function setUp() |
37
|
|
|
{ |
38
|
|
|
global $mockRandomPseudoBytes; |
|
|
|
|
39
|
|
|
|
40
|
|
|
$mockRandomPseudoBytes = false; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Cases provider for token generation. |
45
|
|
|
*/ |
46
|
|
|
public function generateCaseProvider() |
47
|
|
|
{ |
48
|
|
|
return array( |
49
|
|
|
'openssl_pseudo_bytes' => array(false, 50, 100), |
50
|
|
|
'mt_rand_sha_512' => array(true, 64, 100), |
51
|
|
|
); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Tests generate() method. |
56
|
|
|
* |
57
|
|
|
* @dataProvider generateCaseProvider |
58
|
|
|
*/ |
59
|
|
|
public function testGenerate($enableMock, $tokenLength, $iterations) |
60
|
|
|
{ |
61
|
|
|
global $mockRandomPseudoBytes; |
|
|
|
|
62
|
|
|
|
63
|
|
|
$mockRandomPseudoBytes = $enableMock; |
64
|
|
|
|
65
|
|
|
$generator = new RandomTokenGenerator('mocked_secret'); |
66
|
|
|
$alreadyGenerated = array(); |
67
|
|
|
|
68
|
|
|
for ($i = 0; $i < $iterations; ++$i) { |
69
|
|
|
$token = $generator->generate('test_seed'); |
70
|
|
|
|
71
|
|
|
$this->assertEquals($tokenLength, strlen($token)); |
72
|
|
|
$this->assertNotContains($token, $alreadyGenerated); |
73
|
|
|
|
74
|
|
|
$alreadyGenerated[] = $token; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
Instead of relying on
global
state, we recommend one of these alternatives:1. Pass all data via parameters
2. Create a class that maintains your state