forked from Talenttrust/Talenttrust-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreputation-recompute-processor.test.ts
More file actions
299 lines (241 loc) · 12.3 KB
/
Copy pathreputation-recompute-processor.test.ts
File metadata and controls
299 lines (241 loc) · 12.3 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
/**
* Reputation Recompute Processor Tests
*
* Covers:
* - Empty store → zero work, no error
* - Single page (ids fit in one batch)
* - Multi-page (ids span several batches → pagination is exercised)
* - Per-subject error isolation (one failing subject does not abort the batch)
* - Checkpoint writes (createCheckpoint, updateProgress, markCompleted are called)
* - forceRecompute vs. skip-if-recent logic
*/
import { processReputationRecompute } from './reputation-recompute-processor';
import { reputationCheckpointStore } from '../../models/reputation-checkpoint.store';
import { reputationStore } from '../../models/reputation.store';
import { ReputationRepository } from '../../repositories/reputationRepository';
import { ReputationService } from '../../services/reputation.service';
// ── logger mock ──────────────────────────────────────────────────────────────
jest.mock('../../logger', () => ({
createLogger: () => ({
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
}),
}));
// ── ReputationService mock ───────────────────────────────────────────────────
jest.mock('../../services/reputation.service', () => ({
ReputationService: {
getProfile: jest.fn(),
},
}));
const mockGetProfile = ReputationService.getProfile as jest.Mock;
// ── helpers ──────────────────────────────────────────────────────────────────
/**
* Build a minimal mock ReputationRepository whose getDistinctTargetIdPage
* returns pages drawn from `ids` using the supplied limit/offset.
*/
function makeRepo(ids: string[]): jest.Mocked<Pick<ReputationRepository, 'getDistinctTargetIdPage'>> {
return {
getDistinctTargetIdPage: jest.fn((limit: number, offset: number) =>
ids.slice(offset, offset + limit)
),
} as unknown as jest.Mocked<Pick<ReputationRepository, 'getDistinctTargetIdPage'>>;
}
/** Returns a fresh profile stamped "48 hours ago" (stale → eligible for recompute). */
function staleProfile(id: string) {
return {
freelancerId: id,
score: 4.0,
jobsCompleted: 0,
totalRatings: 1,
reviews: [{ reviewerId: 'r1', rating: 4, createdAt: '2023-01-01T00:00:00.000Z' }],
lastUpdated: new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString(),
weightedScore: 4.0,
scoreAlgorithm: 'exp-decay-v1',
};
}
/** Returns a fresh profile stamped "just now" (recent → skipped unless force). */
function freshProfile(id: string) {
return {
...staleProfile(id),
lastUpdated: new Date().toISOString(),
};
}
// ── setup ────────────────────────────────────────────────────────────────────
beforeEach(() => {
reputationCheckpointStore.clear();
reputationStore.clear();
jest.clearAllMocks();
});
// ── empty store ──────────────────────────────────────────────────────────────
describe('empty store', () => {
it('returns success with zero counts and writes no checkpoint progress', async () => {
const updateSpy = jest.spyOn(reputationCheckpointStore, 'updateProgress');
const repo = makeRepo([]);
const result = await processReputationRecompute(
{ batchSize: 10, forceRecompute: false, resumeFromCheckpoint: false },
repo as unknown as ReputationRepository
);
expect(result.success).toBe(true);
expect(result.data).toMatchObject({ totalProcessed: 0, totalFreelancers: 0 });
expect(updateSpy).not.toHaveBeenCalled();
});
});
// ── single-page scenario ─────────────────────────────────────────────────────
describe('single page', () => {
it('processes all IDs when they fit in one batch', async () => {
const ids = ['u1', 'u2', 'u3'];
const repo = makeRepo(ids);
mockGetProfile.mockImplementation(staleProfile);
const result = await processReputationRecompute(
{ batchSize: 10, forceRecompute: true, resumeFromCheckpoint: false },
repo as unknown as ReputationRepository
);
expect(result.success).toBe(true);
expect((result.data as Record<string, unknown>).totalProcessed).toBe(3);
// 3 ids < pageSize=10 → generator exits after the first partial page (no extra sentinel call)
expect(repo.getDistinctTargetIdPage).toHaveBeenCalledTimes(1);
});
it('calls getDistinctTargetIdPage with correct limit and offset', async () => {
const repo = makeRepo(['a', 'b']);
mockGetProfile.mockImplementation(staleProfile);
await processReputationRecompute(
{ batchSize: 50, forceRecompute: true, resumeFromCheckpoint: false },
repo as unknown as ReputationRepository
);
// 2 ids < pageSize=50 → single call, no continuation needed
expect(repo.getDistinctTargetIdPage).toHaveBeenCalledTimes(1);
expect(repo.getDistinctTargetIdPage).toHaveBeenNthCalledWith(1, 50, 0);
});
});
// ── multi-page scenario ──────────────────────────────────────────────────────
describe('multi-page pagination', () => {
it('iterates all pages and processes every subject exactly once', async () => {
const ids = Array.from({ length: 7 }, (_, i) => `subject-${i}`);
const repo = makeRepo(ids);
mockGetProfile.mockImplementation(staleProfile);
const result = await processReputationRecompute(
{ batchSize: 3, forceRecompute: true, resumeFromCheckpoint: false },
repo as unknown as ReputationRepository
);
expect(result.success).toBe(true);
expect((result.data as Record<string, unknown>).totalProcessed).toBe(7);
// pages: [0-2]=full, [3-5]=full, [6]=partial → 3 calls (partial page exits loop)
expect(repo.getDistinctTargetIdPage).toHaveBeenCalledTimes(3);
expect(repo.getDistinctTargetIdPage).toHaveBeenNthCalledWith(1, 3, 0);
expect(repo.getDistinctTargetIdPage).toHaveBeenNthCalledWith(2, 3, 3);
expect(repo.getDistinctTargetIdPage).toHaveBeenNthCalledWith(3, 3, 6);
});
});
// ── per-subject error isolation ──────────────────────────────────────────────
describe('per-subject error isolation', () => {
it('continues processing remaining subjects when one throws', async () => {
const ids = ['good-1', 'bad', 'good-2'];
const repo = makeRepo(ids);
mockGetProfile.mockImplementation((id: string) => {
if (id === 'bad') throw new Error('db error');
return staleProfile(id);
});
const result = await processReputationRecompute(
{ batchSize: 10, forceRecompute: true, resumeFromCheckpoint: false },
repo as unknown as ReputationRepository
);
// job succeeds overall; two subjects processed, one skipped
expect(result.success).toBe(true);
expect((result.data as Record<string, unknown>).totalProcessed).toBe(2);
});
it('processes zero subjects gracefully when all throw', async () => {
const repo = makeRepo(['x', 'y']);
mockGetProfile.mockImplementation(() => { throw new Error('boom'); });
const result = await processReputationRecompute(
{ batchSize: 10, forceRecompute: true, resumeFromCheckpoint: false },
repo as unknown as ReputationRepository
);
expect(result.success).toBe(true);
expect((result.data as Record<string, unknown>).totalProcessed).toBe(0);
});
});
// ── checkpoint writes ────────────────────────────────────────────────────────
describe('checkpoint writes', () => {
it('creates a checkpoint, updates progress per subject, and marks completed', async () => {
const ids = ['s1', 's2'];
const repo = makeRepo(ids);
mockGetProfile.mockImplementation(staleProfile);
const createSpy = jest.spyOn(reputationCheckpointStore, 'createCheckpoint');
const updateSpy = jest.spyOn(reputationCheckpointStore, 'updateProgress');
const completeSpy = jest.spyOn(reputationCheckpointStore, 'markCompleted');
const result = await processReputationRecompute(
{ batchSize: 10, forceRecompute: true, resumeFromCheckpoint: false },
repo as unknown as ReputationRepository
);
expect(createSpy).toHaveBeenCalledTimes(1);
expect(updateSpy).toHaveBeenCalledTimes(2); // once per subject
expect(completeSpy).toHaveBeenCalledTimes(1);
expect(result.data).toHaveProperty('checkpointId');
});
it('reuses the active checkpoint when resumeFromCheckpoint is true', async () => {
const existingCp = reputationCheckpointStore.createCheckpoint('existing-job', 100);
// leave it in 'running' state
const createSpy = jest.spyOn(reputationCheckpointStore, 'createCheckpoint');
const repo = makeRepo(['id1']);
mockGetProfile.mockImplementation(staleProfile);
await processReputationRecompute(
{ batchSize: 10, forceRecompute: true, resumeFromCheckpoint: true },
repo as unknown as ReputationRepository
);
// Should not have called createCheckpoint again (existing active checkpoint reused)
expect(createSpy).toHaveBeenCalledTimes(1); // the one we set up above
const resultCp = reputationCheckpointStore.getCheckpoint(existingCp.jobId);
expect(resultCp?.status).toBe('completed');
});
it('creates a fresh checkpoint when resumeFromCheckpoint is false even if active one exists', async () => {
reputationCheckpointStore.createCheckpoint('old-job', 50);
const createSpy = jest.spyOn(reputationCheckpointStore, 'createCheckpoint');
const repo = makeRepo(['id1']);
mockGetProfile.mockImplementation(staleProfile);
await processReputationRecompute(
{ batchSize: 10, forceRecompute: true, resumeFromCheckpoint: false },
repo as unknown as ReputationRepository
);
expect(createSpy).toHaveBeenCalledTimes(2); // old + new
});
});
// ── skip-if-recent logic ─────────────────────────────────────────────────────
describe('forceRecompute flag', () => {
it('skips recently updated profiles when forceRecompute is false', async () => {
const ids = ['recent-1', 'recent-2'];
const repo = makeRepo(ids);
mockGetProfile.mockImplementation(freshProfile); // last updated = now
const result = await processReputationRecompute(
{ batchSize: 10, forceRecompute: false, resumeFromCheckpoint: false },
repo as unknown as ReputationRepository
);
expect(result.success).toBe(true);
expect((result.data as Record<string, unknown>).totalProcessed).toBe(0);
});
it('processes all profiles when forceRecompute is true regardless of recency', async () => {
const ids = ['recent-1', 'recent-2'];
const repo = makeRepo(ids);
mockGetProfile.mockImplementation(freshProfile);
const result = await processReputationRecompute(
{ batchSize: 10, forceRecompute: true, resumeFromCheckpoint: false },
repo as unknown as ReputationRepository
);
expect(result.success).toBe(true);
expect((result.data as Record<string, unknown>).totalProcessed).toBe(2);
});
});
// ── persists profile to store ─────────────────────────────────────────────────
describe('store persistence', () => {
it('writes the profile returned by ReputationService.getProfile into the reputation store', async () => {
const ids = ['target-x'];
const repo = makeRepo(ids);
const profile = staleProfile('target-x');
mockGetProfile.mockReturnValue(profile);
await processReputationRecompute(
{ batchSize: 10, forceRecompute: true, resumeFromCheckpoint: false },
repo as unknown as ReputationRepository
);
expect(reputationStore.get('target-x')).toEqual(profile);
});
});