-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathglobalStats.test.js
More file actions
323 lines (259 loc) · 9.92 KB
/
globalStats.test.js
File metadata and controls
323 lines (259 loc) · 9.92 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
const GlobalStatsService = require('./src/services/globalStatsService');
const GlobalStatsWorker = require('./src/services/globalStatsWorker');
const { AppDatabase } = require('./src/db/appDatabase');
// Mock Redis for testing
const mockRedis = {
data: new Map(),
get: jest.fn((key) => {
return Promise.resolve(mockRedis.data.get(key) || null);
}),
setex: jest.fn((key, ttl, value) => {
mockRedis.data.set(key, value);
return Promise.resolve('OK');
}),
del: jest.fn((...keys) => {
keys.forEach(key => mockRedis.data.delete(key));
return Promise.resolve(keys.length);
}),
ttl: jest.fn((key) => {
return Promise.resolve(mockRedis.data.has(key) ? 45 : -2);
}),
pipeline: jest.fn(() => ({
setex: jest.fn(),
exec: jest.fn(() => Promise.resolve([]))
}))
};
// Mock database
const mockDatabase = {
db: {
prepare: jest.fn(() => ({
get: jest.fn(() => ({ totalFlow: 1000, totalUsers: 500, totalCreators: 50, totalVideos: 200, totalSubscriptions: 300 })),
all: jest.fn(() => [
{ id: 'creator1', subscriber_count: 100, video_count: 10, latest_video_date: '2024-01-15T10:00:00Z' },
{ id: 'creator2', subscriber_count: 80, video_count: 8, latest_video_date: '2024-01-14T15:30:00Z' }
])
}))
})
};
describe('GlobalStatsService', () => {
let globalStatsService;
beforeEach(() => {
jest.clearAllMocks();
mockRedis.data.clear();
globalStatsService = new GlobalStatsService(mockDatabase, mockRedis);
});
describe('getCachedStats', () => {
it('should return null when cache is empty', async () => {
mockRedis.get.mockResolvedValue(null);
const result = await globalStatsService.getCachedStats();
expect(result).toBeNull();
});
it('should return cached stats when cache has data', async () => {
const cachedData = {
totalValueLocked: 1000,
trendingCreators: [{ id: 'creator1', subscriberCount: 100 }],
totalUsers: 500,
totalCreators: 50,
totalVideos: 200,
totalSubscriptions: 300,
lastUpdated: '2024-01-15T10:00:00Z'
};
mockRedis.get.mockImplementation((key) => {
const data = {
'global_stats:tvl': JSON.stringify(cachedData.totalValueLocked),
'global_stats:trending_creators': JSON.stringify(cachedData.trendingCreators),
'global_stats:total_users': cachedData.totalUsers.toString(),
'global_stats:total_creators': cachedData.totalCreators.toString(),
'global_stats:total_videos': cachedData.totalVideos.toString(),
'global_stats:total_subscriptions': cachedData.totalSubscriptions.toString(),
'global_stats:last_updated': cachedData.lastUpdated
};
return Promise.resolve(data[key] || null);
});
const result = await globalStatsService.getCachedStats();
expect(result).toEqual(cachedData);
});
});
describe('computeFreshStats', () => {
it('should compute fresh statistics from database', async () => {
const result = await globalStatsService.computeFreshStats();
expect(result).toHaveProperty('totalValueLocked');
expect(result).toHaveProperty('trendingCreators');
expect(result).toHaveProperty('totalUsers');
expect(result).toHaveProperty('totalCreators');
expect(result).toHaveProperty('totalVideos');
expect(result).toHaveProperty('totalSubscriptions');
expect(result).toHaveProperty('lastUpdated');
expect(typeof result.totalValueLocked).toBe('number');
expect(Array.isArray(result.trendingCreators)).toBe(true);
expect(typeof result.totalUsers).toBe('number');
});
});
describe('cacheStats', () => {
it('should cache statistics with TTL', async () => {
const stats = {
totalValueLocked: 1000,
trendingCreators: [{ id: 'creator1' }],
totalUsers: 500,
totalCreators: 50,
totalVideos: 200,
totalSubscriptions: 300,
lastUpdated: '2024-01-15T10:00:00Z'
};
await globalStatsService.cacheStats(stats);
expect(mockRedis.pipeline).toHaveBeenCalled();
});
});
describe('getGlobalStats', () => {
it('should return cached stats when available', async () => {
const cachedStats = {
totalValueLocked: 1000,
trendingCreators: [],
totalUsers: 500,
totalCreators: 50,
totalVideos: 200,
totalSubscriptions: 300,
lastUpdated: '2024-01-15T10:00:00Z'
};
mockRedis.get.mockImplementation((key) => {
if (key === 'global_stats:tvl') return Promise.resolve(JSON.stringify(cachedStats.totalValueLocked));
return Promise.resolve(null);
});
jest.spyOn(globalStatsService, 'getCachedStats').mockResolvedValue(cachedStats);
const result = await globalStatsService.getGlobalStats();
expect(result).toEqual(cachedStats);
expect(globalStatsService.getCachedStats).toHaveBeenCalled();
});
it('should compute and cache fresh stats when cache is empty', async () => {
const freshStats = {
totalValueLocked: 1000,
trendingCreators: [],
totalUsers: 500,
totalCreators: 50,
totalVideos: 200,
totalSubscriptions: 300,
lastUpdated: '2024-01-15T10:00:00Z'
};
jest.spyOn(globalStatsService, 'getCachedStats').mockResolvedValue(null);
jest.spyOn(globalStatsService, 'computeAndCacheStats').mockResolvedValue(freshStats);
const result = await globalStatsService.getGlobalStats();
expect(result).toEqual(freshStats);
expect(globalStatsService.getCachedStats).toHaveBeenCalled();
expect(globalStatsService.computeAndCacheStats).toHaveBeenCalled();
});
});
describe('calculateTrendingScore', () => {
it('should calculate trending score correctly', () => {
const creator = {
subscriber_count: 100,
video_count: 10,
latest_video_date: '2024-01-15T10:00:00Z'
};
const score = globalStatsService.calculateTrendingScore(creator);
expect(typeof score).toBe('number');
expect(score).toBeGreaterThan(0);
});
it('should handle creator without latest video', () => {
const creator = {
subscriber_count: 100,
video_count: 10,
latest_video_date: null
};
const score = globalStatsService.calculateTrendingScore(creator);
expect(typeof score).toBe('number');
expect(score).toBeGreaterThanOrEqual(0);
});
});
});
describe('GlobalStatsWorker', () => {
let globalStatsWorker;
let mockGlobalStatsService;
beforeEach(() => {
jest.clearAllMocks();
jest.useFakeTimers();
mockGlobalStatsService = {
refreshCache: jest.fn().mockResolvedValue({
totalCreators: 50,
totalUsers: 500,
totalVideos: 200,
totalSubscriptions: 300,
trendingCreators: []
})
};
globalStatsWorker = new GlobalStatsWorker(mockDatabase);
globalStatsWorker.globalStatsService = mockGlobalStatsService;
});
afterEach(() => {
jest.useRealTimers();
});
describe('start', () => {
it('should start the worker with initial delay', () => {
globalStatsWorker.start();
expect(globalStatsWorker.isRunning).toBe(true);
// Fast-forward past initial delay
jest.advanceTimersByTime(5000);
expect(mockGlobalStatsService.refreshCache).toHaveBeenCalled();
});
it('should not start if already running', () => {
globalStatsWorker.start();
globalStatsWorker.start();
expect(globalStatsWorker.isRunning).toBe(true);
});
});
describe('stop', () => {
it('should stop the worker', () => {
globalStatsWorker.start();
globalStatsWorker.stop();
expect(globalStatsWorker.isRunning).toBe(false);
});
it('should handle stopping when not running', () => {
globalStatsWorker.stop();
expect(globalStatsWorker.isRunning).toBe(false);
});
});
describe('refreshCache', () => {
it('should refresh cache successfully', async () => {
globalStatsWorker.start();
jest.advanceTimersByTime(5000); // Trigger initial refresh
await jest.runAllTimersAsync();
expect(mockGlobalStatsService.refreshCache).toHaveBeenCalled();
});
it('should handle errors and implement backoff', async () => {
mockGlobalStatsService.refreshCache.mockRejectedValue(new Error('Database error'));
globalStatsWorker.start();
jest.advanceTimersByTime(5000); // Trigger initial refresh
await jest.runAllTimersAsync();
expect(globalStatsWorker.errorCount).toBe(1);
expect(globalStatsWorker.currentInterval).toBeGreaterThan(60000);
});
it('should stop after max errors', async () => {
mockGlobalStatsService.refreshCache.mockRejectedValue(new Error('Database error'));
globalStatsWorker.start();
// Trigger multiple errors
for (let i = 0; i < 5; i++) {
jest.advanceTimersByTime(globalStatsWorker.currentInterval);
await jest.runAllTimersAsync();
}
expect(globalStatsWorker.isRunning).toBe(false);
});
});
describe('getStatus', () => {
it('should return worker status', () => {
const status = globalStatsWorker.getStatus();
expect(status).toHaveProperty('isRunning');
expect(status).toHaveProperty('refreshInterval');
expect(status).toHaveProperty('currentInterval');
expect(status).toHaveProperty('errorCount');
expect(status).toHaveProperty('maxErrors');
});
});
describe('resetErrors', () => {
it('should reset error count and interval', () => {
globalStatsWorker.errorCount = 3;
globalStatsWorker.currentInterval = 120000;
globalStatsWorker.resetErrors();
expect(globalStatsWorker.errorCount).toBe(0);
expect(globalStatsWorker.currentInterval).toBe(60000);
});
});
});