2
0

simple-logging.test.ts 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import { describe, it, expect, vi } from 'vitest';
  2. import * as fs from 'fs/promises';
  3. import * as path from 'path';
  4. import { FileLogger } from '@d8d/shared-utils';
  5. // 直接测试文件日志器,不依赖外部模块
  6. describe('文件日志功能测试', () => {
  7. // 模拟 fs 模块
  8. vi.mock('fs/promises', () => ({
  9. mkdir: vi.fn().mockResolvedValue(undefined),
  10. appendFile: vi.fn().mockResolvedValue(undefined)
  11. }));
  12. vi.mock('path', () => ({
  13. join: (...args: string[]) => args.join('/'),
  14. dirname: (filePath: string) => filePath.split('/').slice(0, -1).join('/')
  15. }));
  16. beforeEach(() => {
  17. vi.clearAllMocks();
  18. // 设置环境变量
  19. process.env.LOG_DIR = './test-logs';
  20. });
  21. afterEach(() => {
  22. delete process.env.LOG_DIR;
  23. });
  24. it('应该正确创建日志器实例', () => {
  25. const logger = new FileLogger('test-service');
  26. expect(logger).toBeDefined();
  27. expect(logger).toHaveProperty('info');
  28. expect(logger).toHaveProperty('warn');
  29. expect(logger).toHaveProperty('error');
  30. expect(logger).toHaveProperty('debug');
  31. });
  32. it('应该正确格式化日志消息', async () => {
  33. const logger = new FileLogger('test-service');
  34. // 测试私有方法需要一些技巧,这里我们测试公开方法
  35. const testMessage = '测试消息';
  36. const testMetadata = { key: 'value' };
  37. // 直接调用方法
  38. await logger.info(testMessage, testMetadata);
  39. // 验证 fs.appendFile 被调用
  40. expect(fs.appendFile).toHaveBeenCalled();
  41. const callArgs = (fs.appendFile as any).mock.calls[0];
  42. const filePath = callArgs[0];
  43. const message = callArgs[1];
  44. expect(filePath).toContain('test-service.log');
  45. expect(message).toContain('[INFO]');
  46. expect(message).toContain(testMessage);
  47. expect(message).toContain(JSON.stringify(testMetadata, null, 2));
  48. });
  49. it('应该支持不同的日志级别', async () => {
  50. const logger = new FileLogger('test-service');
  51. await logger.info('信息日志');
  52. await logger.warn('警告日志');
  53. await logger.error('错误日志');
  54. await logger.debug('调试日志');
  55. expect(fs.appendFile).toHaveBeenCalledTimes(4);
  56. // 验证不同级别的日志格式
  57. const calls = (fs.appendFile as any).mock.calls;
  58. expect(calls[0][1]).toContain('[INFO]');
  59. expect(calls[1][1]).toContain('[WARN]');
  60. expect(calls[2][1]).toContain('[ERROR]');
  61. expect(calls[3][1]).toContain('[DEBUG]');
  62. });
  63. it('应该正确处理没有元数据的日志', async () => {
  64. const logger = new FileLogger('test-service');
  65. await logger.info('简单日志');
  66. const callArgs = (fs.appendFile as any).mock.calls[0];
  67. const message = callArgs[1];
  68. expect(message).toContain('[INFO]');
  69. expect(message).toContain('简单日志');
  70. // 不应该包含额外的换行和空对象
  71. expect(message.split('\n').length).toBe(2); // 消息 + 空行
  72. });
  73. it('应该使用自定义日志目录', async () => {
  74. const customLogDir = '/custom/logs';
  75. const logger = new FileLogger('test-service', customLogDir);
  76. await logger.info('测试自定义目录');
  77. const callArgs = (fs.appendFile as any).mock.calls[0];
  78. const filePath = callArgs[0];
  79. expect(filePath).toContain(customLogDir);
  80. });
  81. it('应该在写入失败时不抛出错误', async () => {
  82. const logger = new FileLogger('test-service');
  83. // 模拟写入失败
  84. (fs.appendFile as any).mockRejectedValue(new Error('磁盘已满'));
  85. // 不应该抛出错误
  86. await expect(logger.info('测试错误处理')).resolves.not.toThrow();
  87. });
  88. });