RandomBytesGeneratorTest.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. declare(strict_types=1);
  3. namespace Ramsey\Uuid\Test\Generator;
  4. use Exception;
  5. use Ramsey\Uuid\Exception\RandomSourceException;
  6. use Ramsey\Uuid\Generator\RandomBytesGenerator;
  7. use Ramsey\Uuid\Test\TestCase;
  8. use phpmock\mockery\PHPMockery;
  9. use function hex2bin;
  10. class RandomBytesGeneratorTest extends TestCase
  11. {
  12. /**
  13. * @phpcsSuppress SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingTraversableTypeHintSpecification
  14. */
  15. public function lengthAndHexDataProvider(): array
  16. {
  17. return [
  18. [6, '4f17dd046fb8'],
  19. [10, '4d25f6fe5327cb04267a'],
  20. [12, '1ea89f83bd49cacfdf119e24'],
  21. ];
  22. }
  23. /**
  24. * @param int<1, max> $length
  25. *
  26. * @throws Exception
  27. *
  28. * @dataProvider lengthAndHexDataProvider
  29. * @runInSeparateProcess
  30. * @preserveGlobalState disabled
  31. */
  32. public function testGenerateReturnsRandomBytes(int $length, string $hex): void
  33. {
  34. $bytes = hex2bin($hex);
  35. PHPMockery::mock('Ramsey\Uuid\Generator', 'random_bytes')
  36. ->once()
  37. ->with($length)
  38. ->andReturn($bytes);
  39. $generator = new RandomBytesGenerator();
  40. $this->assertSame($bytes, $generator->generate($length));
  41. }
  42. /**
  43. * @runInSeparateProcess
  44. * @preserveGlobalState disabled
  45. */
  46. public function testGenerateThrowsExceptionWhenExceptionThrownByRandombytes(): void
  47. {
  48. PHPMockery::mock('Ramsey\Uuid\Generator', 'random_bytes')
  49. ->once()
  50. ->with(16)
  51. ->andThrow(new Exception('Could not gather sufficient random data'));
  52. $generator = new RandomBytesGenerator();
  53. $this->expectException(RandomSourceException::class);
  54. $this->expectExceptionMessage('Could not gather sufficient random data');
  55. $generator->generate(16);
  56. }
  57. }