|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace RZ\Roadiz\Random\Tests; |
| 6 | + |
| 7 | +use PHPUnit\Framework\TestCase; |
| 8 | +use Psr\Log\NullLogger; |
| 9 | +use RZ\Roadiz\Random\TokenGenerator; |
| 10 | + |
| 11 | +final class TokenGeneratorTest extends TestCase |
| 12 | +{ |
| 13 | + private function createTokenGenerator(): TokenGenerator |
| 14 | + { |
| 15 | + return new TokenGenerator(new NullLogger()); |
| 16 | + } |
| 17 | + |
| 18 | + /** |
| 19 | + * generateToken() base64-encodes 32 raw bytes (44 chars with padding) then |
| 20 | + * strips the trailing "=" padding, always leaving 43 chars. A regression that |
| 21 | + * shortens the byte count (or the base64 step) would change this length. |
| 22 | + */ |
| 23 | + public function testGenerateTokenLength(): void |
| 24 | + { |
| 25 | + $token = $this->createTokenGenerator()->generateToken(); |
| 26 | + |
| 27 | + self::assertSame(43, \strlen($token)); |
| 28 | + } |
| 29 | + |
| 30 | + public function testGenerateTokenCharset(): void |
| 31 | + { |
| 32 | + $token = $this->createTokenGenerator()->generateToken(); |
| 33 | + |
| 34 | + self::assertMatchesRegularExpression('/^[A-Za-z0-9_-]+$/', $token); |
| 35 | + } |
| 36 | + |
| 37 | + public function testGenerateTokenIsUnique(): void |
| 38 | + { |
| 39 | + $generator = $this->createTokenGenerator(); |
| 40 | + $tokens = []; |
| 41 | + for ($i = 0; $i < 1000; ++$i) { |
| 42 | + $tokens[] = $generator->generateToken(); |
| 43 | + } |
| 44 | + |
| 45 | + self::assertCount(1000, array_unique($tokens)); |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * getRandomNumber() must return raw openssl_random_pseudo_bytes() output (not a |
| 50 | + * time/uniqid-derived string): its length always matches the requested byte count, |
| 51 | + * and RandomGenerator throws instead of falling back if OpenSSL reports non-strong randomness. |
| 52 | + */ |
| 53 | + public function testGetRandomNumberReturnsRequestedByteCount(): void |
| 54 | + { |
| 55 | + $randomNumber = $this->createTokenGenerator()->getRandomNumber(); |
| 56 | + |
| 57 | + self::assertSame(32, \strlen($randomNumber)); |
| 58 | + } |
| 59 | +} |
0 commit comments