-
Notifications
You must be signed in to change notification settings - Fork 368
/
run.service.integration.test.ts
393 lines (354 loc) · 15.9 KB
/
run.service.integration.test.ts
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import { expect, describe, it, beforeAll, afterAll, vi } from 'vitest';
import db from '../../db/database.js';
import SyncRun from './run.service.js';
import environmentService from '../environment.service.js';
import LocalFileService from '../file/local.service.js';
import { SyncStatus, SyncType } from '../../models/Sync.js';
import * as database from '../../db/database.js';
import * as dataMocks from './data/mocks.js';
import * as dataService from './data/data.service.js';
import * as recordsService from './data/records.service.js';
import * as jobService from './job.service.js';
import * as configService from './config/config.service.js';
import type { CustomerFacingDataRecord, IntegrationServiceInterface, Sync, Job as SyncJob, SyncResult } from '../../models/Sync.js';
import type { Environment } from '../../models/Environment.js';
import type { DataResponse } from '../../models/Data.js';
import type { Connection } from '../../models/Connection.js';
class integrationServiceMock implements IntegrationServiceInterface {
async runScript() {
return {
success: true
};
}
async cancelScript() {
return;
}
}
class bigQueryClientMock {
async insert() {
return;
}
}
const integrationService = new integrationServiceMock();
const bigQueryClient = new bigQueryClientMock();
describe('Running sync', () => {
beforeAll(async () => {
await database.multipleMigrations();
});
afterAll(async () => {
await clearDb();
});
describe(`with track_deletes=false`, () => {
const trackDeletes = false;
it(`should report no records have changed`, async () => {
const rawRecords = [
{ id: '1', name: 'a' },
{ id: '2', name: 'b' }
];
const expectedResult = { added: 0, updated: 0, deleted: 0 };
const { records } = await verifySyncRun(rawRecords, rawRecords, trackDeletes, expectedResult);
records.forEach((record) => {
expect(record._nango_metadata.first_seen_at).toEqual(record._nango_metadata.last_modified_at);
expect(record._nango_metadata.deleted_at).toBeNull();
expect(record._nango_metadata.last_action).toEqual('ADDED');
});
});
it(`should report one record has been added and one modified`, async () => {
const rawRecords = [
{ id: '1', name: 'a' },
{ id: '2', name: 'b' }
];
const newRecords = [
{ id: '1', name: 'A' },
{ id: '3', name: 'c' }
];
const expectedResult = { added: 1, updated: 1, deleted: 0 };
const { records } = await verifySyncRun(rawRecords, newRecords, trackDeletes, expectedResult);
const record1 = records.find((record) => record.id == 1);
if (!record1) throw new Error('record1 is not defined');
expect(record1['name']).toEqual('A');
expect(record1._nango_metadata.first_seen_at < record1._nango_metadata.last_modified_at).toBeTruthy();
expect(record1._nango_metadata.deleted_at).toBeNull();
expect(record1._nango_metadata.last_action).toEqual('UPDATED');
const record2 = records.find((record) => record.id == 2);
if (!record2) throw new Error('record2 is not defined');
expect(record2._nango_metadata.first_seen_at).toEqual(record2._nango_metadata.last_modified_at);
expect(record2._nango_metadata.last_action).toEqual('ADDED'); // record was added as part of the initial save
const record3 = records.find((record) => record.id == 3);
if (!record3) throw new Error('record3 is not defined');
expect(record3._nango_metadata.first_seen_at).toEqual(record3._nango_metadata.last_modified_at);
expect(record3._nango_metadata.last_action).toEqual('ADDED');
});
});
describe(`with track_deletes=true`, () => {
const trackDeletes = true;
it(`should report no records have changed`, async () => {
const rawRecords = [
{ id: '1', name: 'a' },
{ id: '2', name: 'b' }
];
const expectedResult = { added: 0, updated: 0, deleted: 0 };
const { records } = await verifySyncRun(rawRecords, rawRecords, trackDeletes, expectedResult);
expect(records).lengthOf(2);
records.forEach((record) => {
expect(record._nango_metadata.first_seen_at).toEqual(record._nango_metadata.last_modified_at);
expect(record._nango_metadata.deleted_at).toBeNull();
expect(record._nango_metadata.last_action).toEqual('ADDED');
});
});
it(`should report one record has been added, one updated and one deleted`, async () => {
const rawRecords = [
{ id: '1', name: 'a' },
{ id: '2', name: 'b' }
];
const newRecords = [
{ id: '1', name: 'A' },
{ id: '3', name: 'c' }
];
const expectedResult = { added: 1, updated: 1, deleted: 1 };
const { records } = await verifySyncRun(rawRecords, newRecords, trackDeletes, expectedResult);
const record1 = records.find((record) => record.id == 1);
if (!record1) throw new Error('record1 is not defined');
expect(record1['name']).toEqual('A');
expect(record1._nango_metadata.first_seen_at < record1._nango_metadata.last_modified_at).toBeTruthy();
expect(record1._nango_metadata.deleted_at).toBeNull();
expect(record1._nango_metadata.last_action).toEqual('UPDATED');
const record2 = records.find((record) => record.id == 2);
if (!record2) throw new Error('record2 is not defined');
expect(record2._nango_metadata.first_seen_at < record2._nango_metadata.last_modified_at).toBeTruthy();
expect(record2._nango_metadata.deleted_at).not.toBeNull();
expect(record2._nango_metadata.last_action).toEqual('DELETED');
const record3 = records.find((record) => record.id == 3);
if (!record3) throw new Error('record3 is not defined');
expect(record3._nango_metadata.first_seen_at).toEqual(record3._nango_metadata.last_modified_at);
expect(record3._nango_metadata.last_action).toEqual('ADDED');
});
it(`should undelete record`, async () => {
const initialRecords = [
{ id: '1', name: 'a' },
{ id: '2', name: 'b' }
];
const expectedResult = { added: 0, updated: 0, deleted: 0 };
const { connection, sync, model, activityLogId } = await verifySyncRun(initialRecords, initialRecords, false, expectedResult);
// records '2' is going to be deleted
const newRecords = [{ id: '1', name: 'a' }];
await runJob(newRecords, activityLogId, model, connection, sync, trackDeletes, false);
const records = await getRecords(connection, model);
const record = records.find((record) => record.id == 2);
if (!record) throw new Error('record is not defined');
expect(record._nango_metadata.first_seen_at < record._nango_metadata.last_modified_at).toBeTruthy();
expect(record._nango_metadata.deleted_at).not.toBeNull();
expect(record._nango_metadata.last_action).toEqual('DELETED');
// records '2' should be back
const result = await runJob(initialRecords, activityLogId, model, connection, sync, trackDeletes, false);
expect(result).toEqual({ added: 1, updated: 0, deleted: 0 });
const recordsAfter = await getRecords(connection, model);
const recordAfter = recordsAfter.find((record) => record.id == 2);
if (!recordAfter) throw new Error('record is not defined');
expect(recordAfter._nango_metadata.first_seen_at).toEqual(recordAfter._nango_metadata.last_modified_at);
expect(recordAfter._nango_metadata.deleted_at).toBeNull();
expect(recordAfter._nango_metadata.last_action).toEqual('ADDED');
});
});
describe(`with softDelete=true`, () => {
const softDelete = true;
it(`should report records have been deleted`, async () => {
const rawRecords = [
{ id: '1', name: 'a' },
{ id: '2', name: 'b' }
];
const expectedResult = { added: 0, updated: 0, deleted: 2 };
const { records } = await verifySyncRun(rawRecords, rawRecords, false, expectedResult, softDelete);
expect(records).lengthOf(2);
records.forEach((record) => {
expect(record._nango_metadata.deleted_at).toEqual(record._nango_metadata.last_modified_at);
expect(record._nango_metadata.deleted_at).not.toBeNull();
expect(record._nango_metadata.last_action).toEqual('DELETED');
});
});
});
});
describe('SyncRun', () => {
const dryRunConfig = {
bigQueryClient,
integrationService: integrationService as unknown as IntegrationServiceInterface,
writeToDb: false,
nangoConnection: {
id: 1,
connection_id: '1234',
provider_config_key: 'test_key',
environment_id: 1
},
syncName: 'test_sync',
syncType: SyncType.INCREMENTAL,
syncId: 'some-sync',
syncJobId: 123,
activityLogId: 123,
debug: true
};
it('should initialize correctly', () => {
const config = {
integrationService: integrationService as unknown as IntegrationServiceInterface,
bigQueryClient,
writeToDb: true,
nangoConnection: {
id: 1,
connection_id: '1234',
provider_config_key: 'test_key',
environment_id: 1
},
syncName: 'test_sync',
syncType: SyncType.INCREMENTAL,
syncId: 'some-sync',
syncJobId: 123,
activityLogId: 123,
loadLocation: '/tmp',
debug: true
};
const syncRun = new SyncRun(config);
expect(syncRun).toBeTruthy();
expect(syncRun.writeToDb).toEqual(true);
expect(syncRun.nangoConnection.connection_id).toEqual('1234');
expect(syncRun.syncName).toEqual('test_sync');
expect(syncRun.syncType).toEqual(SyncType.INCREMENTAL);
expect(syncRun.syncId).toEqual('some-sync');
expect(syncRun.syncJobId).toEqual(123);
expect(syncRun.activityLogId).toEqual(123);
expect(syncRun.loadLocation).toEqual('/tmp');
expect(syncRun.debug).toEqual(true);
});
it('should mock the run method in dry run mode with different fail and success conditions', async () => {
const syncRun = new SyncRun(dryRunConfig);
vi.spyOn(environmentService, 'getById').mockImplementation(() => {
return Promise.resolve({
id: 1,
name: 'test',
account_id: 1,
secret_key: '1234'
} as Environment);
});
vi.spyOn(configService, 'getSyncConfig').mockImplementation(() => {
return Promise.resolve({
integrations: {
test_key: {
test_sync: {
runs: 'every 6h',
returns: ['Foo']
}
}
},
models: {
Foo: {
name: 'Foo'
}
}
});
});
vi.spyOn(LocalFileService, 'checkForIntegrationDistFile').mockImplementation(() => {
return {
result: true,
path: '/tmp'
};
});
vi.spyOn(integrationService, 'runScript').mockImplementation(() => {
return Promise.resolve({
success: true,
response: { success: true }
});
});
const run = await syncRun.run();
expect(run).toEqual({ success: true });
// if integration file not found it should return false
vi.spyOn(LocalFileService, 'checkForIntegrationDistFile').mockImplementation(() => {
return {
result: false,
path: '/tmp'
};
});
const failRun = await syncRun.run();
expect(failRun.response).toEqual(false);
// @ts-expect-error - if run script returns null then fail
vi.spyOn(integrationService, 'runScript').mockImplementation(() => {
return Promise.resolve(null);
});
const { response } = await syncRun.run();
expect(response).toEqual(false);
});
});
const clearDb = async () => {
await db.knex.raw(`DROP SCHEMA nango CASCADE`);
};
const runJob = async (
rawRecords: DataResponse[],
activityLogId: number,
model: string,
connection: Connection,
sync: Sync,
trackDeletes: boolean,
softDelete: boolean
): Promise<SyncResult> => {
// create new sync job
const syncJob = (await jobService.createSyncJob(sync.id, SyncType.INCREMENTAL, SyncStatus.RUNNING, 'test-job-id', connection)) as SyncJob;
if (!syncJob) {
throw new Error('Fail to create sync job');
}
const config = {
integrationService: integrationService,
bigQueryClient,
writeToDb: true,
nangoConnection: connection,
syncName: sync.name,
syncType: SyncType.INITIAL,
syncId: sync.id,
syncJobId: syncJob.id,
activityLogId
};
const syncRun = new SyncRun(config);
// format and upsert records
const { response: records } = recordsService.formatDataRecords(rawRecords, connection.id!, model, sync.id, syncJob.id, softDelete);
if (!records) {
throw new Error(`failed to format records`);
}
const { error: upsertError, summary } = await dataService.upsert(records, connection.id!, model, activityLogId, connection.environment_id, softDelete);
if (upsertError) {
throw new Error(`failed to upsert records: ${upsertError}`);
}
const updatedResults = {
[model]: {
added: summary?.addedKeys.length as number,
updated: summary?.updatedKeys.length as number,
deleted: summary?.deletedKeys?.length as number
}
};
await jobService.updateSyncJobResult(syncJob.id, updatedResults, model);
// finish the sync
await syncRun.finishSync([model], new Date(), `v1`, 10, trackDeletes);
const syncJobResult = await jobService.getLatestSyncJob(sync.id);
return {
added: syncJobResult?.result?.[model]?.added || 0,
updated: syncJobResult?.result?.[model]?.updated || 0,
deleted: syncJobResult?.result?.[model]?.deleted || 0
};
};
const verifySyncRun = async (
initialRecords: DataResponse[],
newRecords: DataResponse[],
trackDeletes: boolean,
expectedResult: SyncResult,
softDelete: boolean = false
): Promise<{ connection: Connection; model: string; sync: Sync; activityLogId: number; records: CustomerFacingDataRecord[] }> => {
// Write initial records
const { connection, model, sync, activityLogId } = await dataMocks.upsertRecords(initialRecords);
// Run job to save new records
const result = await runJob(newRecords, activityLogId, model, connection, sync, trackDeletes, softDelete);
expect(result).toEqual(expectedResult);
const records = await getRecords(connection, model);
return { connection, model, sync, activityLogId, records };
};
const getRecords = async (connection: Connection, model: string) => {
const { response } = await recordsService.getAllDataRecords(connection.connection_id, connection.provider_config_key, connection.environment_id, model);
if (response) {
return response.records;
}
throw new Error('cannot fetch records');
};