DefaultNameGeneratorTest.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. declare(strict_types=1);
  3. namespace Ramsey\Uuid\Test\Generator;
  4. use Ramsey\Uuid\Exception\NameException;
  5. use Ramsey\Uuid\Generator\DefaultNameGenerator;
  6. use Ramsey\Uuid\Test\TestCase;
  7. use Ramsey\Uuid\Uuid;
  8. use function hash;
  9. class DefaultNameGeneratorTest extends TestCase
  10. {
  11. /**
  12. * @param non-empty-string $ns
  13. *
  14. * @dataProvider provideNamesForHashingTest
  15. */
  16. public function testDefaultNameGeneratorHashesName(string $ns, string $name, string $algorithm): void
  17. {
  18. $namespace = Uuid::fromString($ns);
  19. $expectedBytes = hash($algorithm, $namespace->getBytes() . $name, true);
  20. $generator = new DefaultNameGenerator();
  21. $this->assertSame($expectedBytes, $generator->generate($namespace, $name, $algorithm));
  22. }
  23. /**
  24. * @phpcsSuppress SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingTraversableTypeHintSpecification
  25. */
  26. public function provideNamesForHashingTest(): array
  27. {
  28. return [
  29. [
  30. 'ns' => Uuid::NAMESPACE_URL,
  31. 'name' => 'https://example.com/foobar',
  32. 'algorithm' => 'md5',
  33. ],
  34. [
  35. 'ns' => Uuid::NAMESPACE_URL,
  36. 'name' => 'https://example.com/foobar',
  37. 'algorithm' => 'sha1',
  38. ],
  39. [
  40. 'ns' => Uuid::NAMESPACE_URL,
  41. 'name' => 'https://example.com/foobar',
  42. 'algorithm' => 'sha256',
  43. ],
  44. [
  45. 'ns' => Uuid::NAMESPACE_OID,
  46. 'name' => '1.3.6.1.4.1.343',
  47. 'algorithm' => 'sha1',
  48. ],
  49. [
  50. 'ns' => Uuid::NAMESPACE_OID,
  51. 'name' => '1.3.6.1.4.1.52627',
  52. 'algorithm' => 'md5',
  53. ],
  54. [
  55. 'ns' => 'd988ae29-674e-48e7-b93c-2825e2a96fbe',
  56. 'name' => 'foobar',
  57. 'algorithm' => 'sha1',
  58. ],
  59. ];
  60. }
  61. public function testGenerateThrowsException(): void
  62. {
  63. $namespace = Uuid::fromString('cd998804-c661-4264-822c-00cada75a87b');
  64. $generator = new DefaultNameGenerator();
  65. $this->expectException(NameException::class);
  66. $this->expectExceptionMessage(
  67. 'Unable to hash namespace and name with algorithm \'aBadAlgorithm\''
  68. );
  69. $generator->generate($namespace, 'a test name', 'aBadAlgorithm');
  70. }
  71. }