Files
php-uuid/tests/Generator/RandomBytesGeneratorTest.php
T
Marco Pivetta a252f29847 Import used functions and constants via use statement to disallow ambiguity for compiler/static-analysis
As documented in https://wiki.php.net/rfc/use_global_elements, the engine (by default) does a local namespace
lookup, then falls back to global namespace when first calling a global function referenced in namespaced code,
unless that function is referenced via fully qualified name (FQN).

By using the FQN, the actual symbol can be looked up at compile-time, both by the PHP engine and by static analysis
tooling, allowing for compiler (in particular) optimizations to replace known hot-path functions with specialized opcodes.

Sadly, no actual benchmark at hand: the improvements can be minimal or massive, depending on where this library is
used (tight loops being most relevant).
2020-02-03 13:15:35 -06:00

79 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use AspectMock\Test as AspectMock;
use Exception;
use Ramsey\Uuid\Exception\RandomSourceException;
use Ramsey\Uuid\Generator\RandomBytesGenerator;
use Ramsey\Uuid\Test\TestCase;
use function hex2bin;
class RandomBytesGeneratorTest extends TestCase
{
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingTraversableTypeHintSpecification
*/
public function lengthAndHexDataProvider(): array
{
return [
[6, '4f17dd046fb8'],
[10, '4d25f6fe5327cb04267a'],
[12, '1ea89f83bd49cacfdf119e24'],
];
}
/**
* @throws Exception
*
* @dataProvider lengthAndHexDataProvider
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGenerateUsesOpenSsl(int $length, string $hex): void
{
$bytes = hex2bin($hex);
$openSsl = AspectMock::func('Ramsey\Uuid\Generator', 'random_bytes', $bytes);
$generator = new RandomBytesGenerator();
$this->assertSame($bytes, $generator->generate($length));
$openSsl->verifyInvokedOnce([$length]);
}
/**
* @throws Exception
*
* @dataProvider lengthAndHexDataProvider
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGenerateReturnsRandomBytes(int $length, string $hex): void
{
$bytes = hex2bin($hex);
AspectMock::func('Ramsey\Uuid\Generator', 'random_bytes', $bytes);
$generator = new RandomBytesGenerator();
$this->assertEquals($bytes, $generator->generate($length));
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGenerateThrowsExceptionWhenExceptionThrownByRandombytes(): void
{
AspectMock::func('Ramsey\Uuid\Generator', 'random_bytes', function (): void {
throw new Exception('Could not gather sufficient random data');
});
$generator = new RandomBytesGenerator();
$this->expectException(RandomSourceException::class);
$this->expectExceptionMessage('Could not gather sufficient random data');
$generator->generate(16);
}
}