|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Tourze\SnowflakeBundle\Tests\Integration; |
| 4 | + |
| 5 | +use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; |
| 6 | +use Tourze\SnowflakeBundle\Service\ResolverFactory; |
| 7 | +use Tourze\SnowflakeBundle\Service\Snowflake; |
| 8 | + |
| 9 | +/** |
| 10 | + * 测试SnowflakeBundle与Symfony框架的集成 |
| 11 | + */ |
| 12 | +class SnowflakeIntegrationTest extends KernelTestCase |
| 13 | +{ |
| 14 | + protected static function getKernelClass(): string |
| 15 | + { |
| 16 | + return IntegrationTestKernel::class; |
| 17 | + } |
| 18 | + |
| 19 | + protected function setUp(): void |
| 20 | + { |
| 21 | + // 启动内核 |
| 22 | + self::bootKernel(); |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * 测试Snowflake服务是否正确注册 |
| 27 | + */ |
| 28 | + public function testSnowflakeServiceRegistration(): void |
| 29 | + { |
| 30 | + $container = static::getContainer(); |
| 31 | + |
| 32 | + // 测试Snowflake服务是否存在 |
| 33 | + $this->assertTrue($container->has(Snowflake::class)); |
| 34 | + |
| 35 | + // 测试ResolverFactory服务是否存在 |
| 36 | + $this->assertTrue($container->has(ResolverFactory::class)); |
| 37 | + |
| 38 | + // 获取Snowflake服务实例 |
| 39 | + $snowflake = $container->get(Snowflake::class); |
| 40 | + $this->assertInstanceOf(Snowflake::class, $snowflake); |
| 41 | + |
| 42 | + // 获取ResolverFactory服务实例 |
| 43 | + $resolverFactory = $container->get(ResolverFactory::class); |
| 44 | + $this->assertInstanceOf(ResolverFactory::class, $resolverFactory); |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * 测试Snowflake服务是否能正确生成雪花ID |
| 49 | + */ |
| 50 | + public function testSnowflakeIdGeneration(): void |
| 51 | + { |
| 52 | + $container = static::getContainer(); |
| 53 | + $snowflake = $container->get(Snowflake::class); |
| 54 | + |
| 55 | + // 生成一个雪花ID |
| 56 | + $id = $snowflake->id(); |
| 57 | + |
| 58 | + // 验证ID是一个非空字符串 |
| 59 | + $this->assertIsString($id); |
| 60 | + $this->assertNotEmpty($id); |
| 61 | + |
| 62 | + // 验证ID是一个数字字符串 |
| 63 | + $this->assertIsNumeric($id); |
| 64 | + |
| 65 | + // 验证ID的长度(应该至少有10位数) |
| 66 | + $this->assertGreaterThan(10, strlen($id)); |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * 测试在短时间内多次调用id方法返回唯一ID |
| 71 | + */ |
| 72 | + public function testSnowflakeIdUniqueness(): void |
| 73 | + { |
| 74 | + $container = static::getContainer(); |
| 75 | + $snowflake = $container->get(Snowflake::class); |
| 76 | + |
| 77 | + $ids = []; |
| 78 | + $count = 10; // 生成10个ID |
| 79 | + |
| 80 | + for ($i = 0; $i < $count; $i++) { |
| 81 | + $ids[] = $snowflake->id(); |
| 82 | + } |
| 83 | + |
| 84 | + // 验证生成的所有ID都是唯一的 |
| 85 | + $uniqueIds = array_unique($ids); |
| 86 | + $this->assertCount($count, $uniqueIds); |
| 87 | + |
| 88 | + // 验证ID是按顺序生成的(每个ID应该大于前一个) |
| 89 | + for ($i = 1; $i < $count; $i++) { |
| 90 | + $this->assertGreaterThan($ids[$i - 1], $ids[$i]); |
| 91 | + } |
| 92 | + } |
| 93 | +} |
0 commit comments