StudentIdServiceTest.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace Tests\Unit;
  3. use App\Services\StudentIdService;
  4. use PHPUnit\Framework\TestCase;
  5. class StudentIdServiceTest extends TestCase
  6. {
  7. /**
  8. * 测试学生ID生成功能
  9. */
  10. public function test_generate_student_id(): void
  11. {
  12. $studentId = StudentIdService::generateStudentId();
  13. // 验证格式
  14. $this->assertTrue(StudentIdService::validateStudentIdFormat($studentId));
  15. // 验证格式模式
  16. $this->assertMatchesRegularExpression('/^stu_\d+_\d+$/', $studentId);
  17. // 验证组成部分
  18. $parts = explode('_', $studentId);
  19. $this->assertEquals('stu', $parts[0]);
  20. $this->assertIsNumeric($parts[1]); // 时间戳
  21. $this->assertIsNumeric($parts[2]); // 序号
  22. }
  23. /**
  24. * 测试生成多个学生ID的唯一性
  25. */
  26. public function test_generate_multiple_student_ids(): void
  27. {
  28. $ids = [];
  29. $count = 10;
  30. for ($i = 0; $i < $count; $i++) {
  31. $id = StudentIdService::generateStudentId();
  32. $this->assertTrue(StudentIdService::validateStudentIdFormat($id));
  33. $this->assertNotContains($id, $ids); // 确保唯一性
  34. $ids[] = $id;
  35. }
  36. $this->assertCount($count, $ids);
  37. $this->assertEquals(count($ids), count(array_unique($ids)));
  38. }
  39. /**
  40. * 测试学生ID格式验证功能
  41. */
  42. public function test_validate_student_id_format(): void
  43. {
  44. // 有效的格式
  45. $validIds = [
  46. 'stu_1234567890_0',
  47. 'stu_1609459200_1',
  48. 'stu_9999999999_999',
  49. ];
  50. foreach ($validIds as $id) {
  51. $this->assertTrue(StudentIdService::validateStudentIdFormat($id), "ID {$id} 应该是有效的");
  52. }
  53. // 无效的格式
  54. $invalidIds = [
  55. 'stu_abc_0', // 非数字时间戳
  56. 'stu_1234567890', // 缺少序号
  57. 'stu_1234567890_abc', // 非数字序号
  58. 'teacher_123_0', // 错误前缀
  59. '1234567890_0', // 缺少前缀
  60. '', // 空字符串
  61. 'stu_', // 缺少时间戳和序号
  62. 'stu__0', // 缺少时间戳
  63. ];
  64. foreach ($invalidIds as $id) {
  65. $this->assertFalse(StudentIdService::validateStudentIdFormat($id), "ID {$id} 应该是无效的");
  66. }
  67. }
  68. /**
  69. * 测试边界情况
  70. */
  71. public function test_edge_cases(): void
  72. {
  73. // 测试生成ID的时间戳部分是否在合理范围内
  74. $id = StudentIdService::generateStudentId();
  75. $parts = explode('_', $id);
  76. $timestamp = (int)$parts[1];
  77. // 验证时间戳是否在最近10年内(合理性检查)
  78. $tenYearsAgo = time() - (10 * 365 * 24 * 60 * 60);
  79. $tenYearsLater = time() + (10 * 365 * 24 * 60 * 60);
  80. $this->assertGreaterThanOrEqual($tenYearsAgo, $timestamp);
  81. $this->assertLessThanOrEqual($tenYearsLater, $timestamp);
  82. // 验证序号是非负整数
  83. $sequence = (int)$parts[2];
  84. $this->assertGreaterThanOrEqual(0, $sequence);
  85. }
  86. }