forked from rinafcode/teachLink_backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.service.spec.ts
More file actions
246 lines (198 loc) · 7.38 KB
/
Copy pathsession.service.spec.ts
File metadata and controls
246 lines (198 loc) · 7.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import { Test, TestingModule } from '@nestjs/testing';
import { ConfigService } from '@nestjs/config';
import { SessionService } from './session.service';
import { SESSION_REDIS_CLIENT } from './session.constants';
const mockRedis = {
get: jest.fn(),
set: jest.fn(),
del: jest.fn(),
expire: jest.fn(),
eval: jest.fn(),
multi: jest.fn(),
zadd: jest.fn().mockResolvedValue(1),
zrem: jest.fn().mockResolvedValue(1),
zrange: jest.fn().mockResolvedValue([]),
scan: jest.fn(),
status: 'ready',
quit: jest.fn(),
};
const mockMulti = {
set: jest.fn().mockReturnThis(),
del: jest.fn().mockReturnThis(),
expire: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue([]),
};
const mockConfigService = {
get: jest.fn((key: string, defaultVal?: string) => {
const values: Record<string, string> = {
AUTH_SESSION_PREFIX: 'auth:sess:',
AUTH_SESSION_LEGACY_PREFIX: 'session:',
AUTH_SESSION_TTL_SECONDS: '604800',
SESSION_LOCK_TTL_MS: '5000',
SESSION_LOCK_MAX_RETRIES: '5',
SESSION_LOCK_RETRY_DELAY_MS: '120',
};
return values[key] ?? defaultVal ?? '';
}),
};
describe('SessionService', () => {
let service: SessionService;
beforeEach(async () => {
mockRedis.multi.mockReturnValue(mockMulti);
const module: TestingModule = await Test.createTestingModule({
providers: [
SessionService,
{ provide: SESSION_REDIS_CLIENT, useValue: mockRedis },
{ provide: ConfigService, useValue: mockConfigService },
],
}).compile();
service = module.get<SessionService>(SessionService);
});
afterEach(() => {
jest.clearAllMocks();
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('createSession', () => {
it('should create a session and return a sid', async () => {
mockRedis.set.mockResolvedValue('OK');
const sid = await service.createSession('user-123', { role: 'student' });
expect(typeof sid).toBe('string');
expect(sid.length).toBeGreaterThan(0);
expect(mockRedis.set).toHaveBeenCalledWith(
expect.stringContaining('auth:sess:'),
expect.any(String),
'EX',
604800,
);
});
it('should store userId and metadata in session payload', async () => {
mockRedis.set.mockResolvedValue('OK');
await service.createSession('user-456', { plan: 'premium' });
const payload = JSON.parse(mockRedis.set.mock.calls[0][1]);
expect(payload.userId).toBe('user-456');
expect(payload.metadata.plan).toBe('premium');
expect(payload.version).toBe(1);
});
});
describe('getSession', () => {
it('should return parsed session when found in Redis', async () => {
const sessionData = {
sid: 'test-sid',
userId: 'user-123',
metadata: {},
version: 1,
createdAt: Date.now(),
updatedAt: Date.now(),
};
mockRedis.get.mockResolvedValue(JSON.stringify(sessionData));
const result = await service.getSession('test-sid');
expect(result).not.toBeNull();
expect(result?.userId).toBe('user-123');
expect(result?.version).toBe(1);
});
it('should return null when session does not exist', async () => {
mockRedis.get.mockResolvedValue(null);
const result = await service.getSession('nonexistent-sid');
expect(result).toBeNull();
});
it('should return null when session payload is invalid JSON', async () => {
mockRedis.get.mockResolvedValue('not-valid-json{{{');
const result = await service.getSession('bad-sid');
expect(result).toBeNull();
});
});
describe('touchSession', () => {
it('should update metadata and increment version', async () => {
const sessionData = {
sid: 'test-sid',
userId: 'user-123',
metadata: { role: 'student' },
version: 1,
createdAt: Date.now(),
updatedAt: Date.now(),
};
mockRedis.get.mockResolvedValue(JSON.stringify(sessionData));
await service.touchSession('test-sid', { lastPage: '/dashboard' });
expect(mockMulti.set).toHaveBeenCalled();
expect(mockMulti.expire).toHaveBeenCalled();
expect(mockMulti.exec).toHaveBeenCalled();
const updatedPayload = JSON.parse(mockMulti.set.mock.calls[0][1]);
expect(updatedPayload.version).toBe(2);
expect(updatedPayload.metadata.lastPage).toBe('/dashboard');
expect(updatedPayload.metadata.role).toBe('student');
});
it('should do nothing when session does not exist', async () => {
mockRedis.get.mockResolvedValue(null);
await service.touchSession('nonexistent-sid');
expect(mockMulti.exec).not.toHaveBeenCalled();
});
});
describe('removeSession', () => {
it('should delete session from Redis', async () => {
mockRedis.del.mockResolvedValue(1);
await service.removeSession('test-sid');
expect(mockRedis.del).toHaveBeenCalledWith('auth:sess:test-sid');
});
});
describe('deleteAllSessionsForUser', () => {
it('should remove all Redis sessions for a user', async () => {
mockRedis.scan.mockResolvedValueOnce(['0', ['auth:sess:one', 'auth:sess:two']]);
mockRedis.get
.mockResolvedValueOnce(JSON.stringify({ sid: 'one', userId: 'user-123' }))
.mockResolvedValueOnce(JSON.stringify({ sid: 'two', userId: 'user-999' }));
mockRedis.del.mockResolvedValue(1);
const deletedCount = await service.deleteAllSessionsForUser('user-123');
expect(deletedCount).toBe(1);
expect(mockRedis.del).toHaveBeenCalledWith('auth:sess:one');
expect(mockRedis.zrem).toHaveBeenCalledWith('user:sessions:user-123', 'one');
});
});
describe('migrateSession', () => {
it('should migrate session to new sid and delete old one', async () => {
const sessionData = {
sid: 'old-sid',
userId: 'user-123',
metadata: {},
version: 1,
createdAt: Date.now(),
updatedAt: Date.now(),
};
mockRedis.get.mockResolvedValue(JSON.stringify(sessionData));
const newSid = await service.migrateSession(
'old-sid',
'00000000-0000-0000-0000-000000000001',
);
expect(newSid).toBe('00000000-0000-0000-0000-000000000001');
expect(mockMulti.set).toHaveBeenCalled();
expect(mockMulti.del).toHaveBeenCalled();
expect(mockMulti.exec).toHaveBeenCalled();
});
it('should return newSid unchanged when old session does not exist', async () => {
mockRedis.get.mockResolvedValue(null);
const newSid = await service.migrateSession(
'nonexistent-sid',
'00000000-0000-0000-0000-000000000001',
);
expect(newSid).toBe('00000000-0000-0000-0000-000000000001');
expect(mockMulti.exec).not.toHaveBeenCalled();
});
});
describe('withLock', () => {
it('should acquire lock and execute handler', async () => {
mockRedis.set.mockResolvedValue('OK');
mockRedis.eval.mockResolvedValue(1);
const handler = jest.fn().mockResolvedValue('result');
const result = await service.withLock('test-lock', handler);
expect(result).toBe('result');
expect(handler).toHaveBeenCalled();
});
it('should throw when lock cannot be acquired', async () => {
mockRedis.set.mockResolvedValue(null);
await expect(service.withLock('busy-lock', jest.fn())).rejects.toThrow(
'Could not acquire lock: busy-lock',
);
});
});
});