| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace Tests\Unit;
- use App\Services\StudentIdService;
- use PHPUnit\Framework\TestCase;
- class StudentIdServiceTest extends TestCase
- {
- /**
- * 测试学生ID生成功能
- */
- public function test_generate_student_id(): void
- {
- $studentId = StudentIdService::generateStudentId();
- // 验证格式
- $this->assertTrue(StudentIdService::validateStudentIdFormat($studentId));
- // 验证格式模式
- $this->assertMatchesRegularExpression('/^stu_\d+_\d+$/', $studentId);
- // 验证组成部分
- $parts = explode('_', $studentId);
- $this->assertEquals('stu', $parts[0]);
- $this->assertIsNumeric($parts[1]); // 时间戳
- $this->assertIsNumeric($parts[2]); // 序号
- }
- /**
- * 测试生成多个学生ID的唯一性
- */
- public function test_generate_multiple_student_ids(): void
- {
- $ids = [];
- $count = 10;
- for ($i = 0; $i < $count; $i++) {
- $id = StudentIdService::generateStudentId();
- $this->assertTrue(StudentIdService::validateStudentIdFormat($id));
- $this->assertNotContains($id, $ids); // 确保唯一性
- $ids[] = $id;
- }
- $this->assertCount($count, $ids);
- $this->assertEquals(count($ids), count(array_unique($ids)));
- }
- /**
- * 测试学生ID格式验证功能
- */
- public function test_validate_student_id_format(): void
- {
- // 有效的格式
- $validIds = [
- 'stu_1234567890_0',
- 'stu_1609459200_1',
- 'stu_9999999999_999',
- ];
- foreach ($validIds as $id) {
- $this->assertTrue(StudentIdService::validateStudentIdFormat($id), "ID {$id} 应该是有效的");
- }
- // 无效的格式
- $invalidIds = [
- 'stu_abc_0', // 非数字时间戳
- 'stu_1234567890', // 缺少序号
- 'stu_1234567890_abc', // 非数字序号
- 'teacher_123_0', // 错误前缀
- '1234567890_0', // 缺少前缀
- '', // 空字符串
- 'stu_', // 缺少时间戳和序号
- 'stu__0', // 缺少时间戳
- ];
- foreach ($invalidIds as $id) {
- $this->assertFalse(StudentIdService::validateStudentIdFormat($id), "ID {$id} 应该是无效的");
- }
- }
- /**
- * 测试边界情况
- */
- public function test_edge_cases(): void
- {
- // 测试生成ID的时间戳部分是否在合理范围内
- $id = StudentIdService::generateStudentId();
- $parts = explode('_', $id);
- $timestamp = (int)$parts[1];
- // 验证时间戳是否在最近10年内(合理性检查)
- $tenYearsAgo = time() - (10 * 365 * 24 * 60 * 60);
- $tenYearsLater = time() + (10 * 365 * 24 * 60 * 60);
- $this->assertGreaterThanOrEqual($tenYearsAgo, $timestamp);
- $this->assertLessThanOrEqual($tenYearsLater, $timestamp);
- // 验证序号是非负整数
- $sequence = (int)$parts[2];
- $this->assertGreaterThanOrEqual(0, $sequence);
- }
- }
|