forked from rudderlabs/rudder-transformer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent.test.ts
More file actions
303 lines (276 loc) · 10.1 KB
/
Copy pathcomponent.test.ts
File metadata and controls
303 lines (276 loc) · 10.1 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
import { join } from 'path';
import Koa from 'koa';
import request from 'supertest';
// Mocking of axios calls
import axios from 'axios';
// new-library we are using
import bodyParser from 'koa-bodyparser';
import { Command } from 'commander';
import { createHttpTerminator } from 'http-terminator';
import { ExtendedTestCaseData, TestCaseData } from './testTypes';
import { applicationRoutes } from '../../src/routes/index';
import MockAxiosAdapter from 'axios-mock-adapter';
import { EnvManager } from './envUtils';
import {
getTestDataFilePaths,
getTestData,
registerAxiosMocks,
validateTestWithZOD,
validateStreamTestWithZOD,
getTestMockData,
} from './testUtils';
import tags from '../../src/v0/util/tags';
import { Server } from 'http';
import { appendFileSync } from 'fs';
import { assertRouterOutput, responses } from '../testHelper';
import { initaliseReport } from '../test_reporter/reporter';
import { FetchHandler } from '../../src/helpers/fetchHandlers';
import { enhancedTestUtils } from '../test_reporter/allureReporter';
import { configureBatchProcessingDefaults, axiosFromLib } from '@rudderstack/integrations-lib';
// To run single destination test cases
// npm run test:ts -- component --destination=adobe_analytics
// npm run test:ts -- component --destination=adobe_analytics --feature=router
// npm run test:ts -- component --destination=adobe_analytics --feature=dataDelivery --index=0
// Use below command to see verbose results
// npm run test:ts -- component --destination=adobe_analytics --feature=router --verbose true
// Use below command to generate mocks
// npm run test:ts -- component --destination=zendesk --generate=true
// npm run test:ts:component:generateNwMocks -- --destination=zendesk
const command = new Command();
command
.allowUnknownOption()
.allowExcessArguments()
.option('-d, --destination <string>', 'Enter Destination Name')
.option('-f, --feature <string>', 'Enter Feature Name(processor, router)')
.option('-i, --index <number>', 'Enter Test index', parseInt)
.option('-g, --generate <string>', 'Enter "true" If you want to generate network file')
.option('--id <string>', 'Enter unique "Id" of the test case you want to run')
.option('-v, --verbose <string>', 'Enter "true" If you want to see verbose test results')
.option('-s, --source <string>', 'Enter Source Name')
.parse();
const opts = command.opts();
if (opts.generate === 'true' && !opts.destination) {
throw new Error('Invalid option, generate should be true for a destination');
}
if (opts.generate === 'true') {
process.env.GEN_AXIOS_FOR_TESTS = 'true';
}
let server: Server;
const INTEGRATIONS_WITH_UPDATED_TEST_STRUCTURE = [
'active_campaign',
'klaviyo',
'campaign_manager',
'criteo_audience',
'customerio_audience',
'branch',
'userpilot',
'loops',
'slack',
'snapchat_conversion',
'rudder_test',
'tiktok_ads',
'bluecore',
'postscript',
'attentive_tag',
'dub',
];
const STREAMING_DEST_WITH_UPDATED_TEST_STRUCTURE = [
'googlesheets',
'kafka',
'kinesis',
'personalize',
'eventbridge',
];
beforeAll(async () => {
initaliseReport();
// Setting batch processing defaults to lower values to make the tests use the batch processing
configureBatchProcessingDefaults({
batchSize: 1,
yieldThreshold: 1,
sequentialProcessing: true,
});
const app = new Koa();
app.use(
bodyParser({
jsonLimit: '200mb',
}),
);
applicationRoutes(app);
server = app.listen();
});
afterAll(async () => {
await createHttpTerminator({ server }).terminate();
if (opts.generate === 'true') {
const callsDataStr = responses.join('\n');
const calls = `
export const networkCallsData = [
${callsDataStr}
]
`;
appendFileSync(join(__dirname, 'destinations', opts.destination, 'network.ts'), calls);
}
});
// END
const rootDir = __dirname;
console.log('rootDir', rootDir);
console.log('opts', opts);
const allTestDataFilePaths = getTestDataFilePaths(rootDir, opts);
const DEFAULT_VERSION = 'v0';
const testRoute = async (route, tcData: TestCaseData) => {
const inputReq = tcData.input.request;
const { headers, params, body } = inputReq;
let testRequest: request.Test;
switch (inputReq.method) {
case 'GET':
testRequest = request(server).get(route);
break;
case 'PUT':
testRequest = request(server).put(route);
break;
case 'DELETE':
testRequest = request(server).delete(route);
break;
default:
testRequest = request(server).post(route);
break;
}
const response = await testRequest
.set(headers || {})
.query(params || {})
.send(body);
const outputResp = tcData.output.response || ({} as any);
expect(response.status).toEqual(outputResp.status);
if (INTEGRATIONS_WITH_UPDATED_TEST_STRUCTURE.includes(tcData.name?.toLocaleLowerCase())) {
expect(validateTestWithZOD(tcData, response)).toEqual(true);
enhancedTestUtils.beforeTestRun(tcData);
enhancedTestUtils.afterTestRun(tcData, response.body, opts.verbose === 'true');
}
if (STREAMING_DEST_WITH_UPDATED_TEST_STRUCTURE.includes(tcData.name?.toLocaleLowerCase())) {
expect(validateStreamTestWithZOD(tcData, response)).toEqual(true);
enhancedTestUtils.beforeTestRun(tcData);
enhancedTestUtils.afterTestRun(tcData, response.body, opts.verbose === 'true');
}
if (outputResp?.body) {
expect(response.body).toEqual(outputResp.body);
}
if (outputResp.headers !== undefined) {
expect(response.headers).toEqual(outputResp.headers);
}
if (tcData.feature === tags.FEATURES.BATCH || tcData.feature === tags.FEATURES.ROUTER) {
//TODO get rid of these skipped destinations after they are fixed
if (
tcData.name != 'marketo_static_list' &&
tcData.name != 'mailmodo' &&
tcData.name != 'iterable' &&
tcData.name != 'klaviyo' &&
tcData.name != 'mailjet' &&
tcData.name != 'google_adwords_offline_conversions'
) {
assertRouterOutput(response.body.output, tcData.input.request.body.input);
}
}
};
const destinationTestHandler = async (tcData: TestCaseData) => {
let route;
switch (tcData.feature) {
case tags.FEATURES.ROUTER:
route = `/routerTransform`;
break;
case tags.FEATURES.BATCH:
route = `/batch`;
break;
case tags.FEATURES.DATA_DELIVERY:
route = `/${join(tcData.version || DEFAULT_VERSION, 'destinations', tcData.name, 'proxy')}`;
break;
case tags.FEATURES.USER_DELETION:
route = '/deleteUsers';
break;
case tags.FEATURES.PROCESSOR:
// Processor transformation
route = `/${join(tcData.version || DEFAULT_VERSION, 'destinations', tcData.name)}`;
break;
default:
// Intentionally fail the test case
expect(true).toEqual(false);
break;
}
route = join(route, tcData.input.pathSuffix || '');
await testRoute(route, tcData);
};
const sourceTestHandler = async (tcData) => {
const route = `/${join(tcData.version || 'v2', 'sources', tcData.name, tcData.input.pathSuffix || '')}`;
await testRoute(route, tcData);
};
const mockAdapter = new MockAxiosAdapter(axios as any, { onNoMatch: 'throwException' });
registerAxiosMocks(mockAdapter, getTestMockData(opts.destination || opts.source));
const mockAxiosFromLib = new MockAxiosAdapter(axiosFromLib as any, { onNoMatch: 'throwException' });
registerAxiosMocks(mockAxiosFromLib, getTestMockData(opts.destination || opts.source));
describe('Component Test Suite', () => {
if (allTestDataFilePaths.length === 0) {
// Reason: No test cases matched the given criteria
test.skip('No test cases provided. Skipping tests.', () => {});
} else {
describe.each(allTestDataFilePaths)('%s Tests', (testDataPath) => {
afterEach(() => {
jest.resetAllMocks();
jest.clearAllMocks();
});
let testData: TestCaseData[] = getTestData(testDataPath);
if (opts.index < testData.length && opts.index >= 0) {
testData = [testData[opts.index]];
}
if (opts.id) {
testData = testData.filter((data) => data.id === opts.id);
}
const extendedTestData: ExtendedTestCaseData[] = testData.flatMap((tcData) => {
return [{ tcData, descriptionSuffix: '' }];
});
if (extendedTestData.length === 0) {
// Reason: user may have skipped the test cases
test.skip('No test cases provided. Skipping tests.', () => {});
} else {
describe(`${testData[0].name} ${testData[0].module}`, () => {
test.each(extendedTestData)(
'$tcData.feature -> $tcData.description$descriptionSuffix (index: $#)',
async ({ tcData }) => {
const envManager = new EnvManager();
const testId = `${tcData.id || tcData.name}-${Date.now()}`;
try {
// Handle environment variable overrides if present
if (tcData.envOverrides) {
const envKeys = Object.keys(tcData.envOverrides);
envManager.takeSnapshot(testId, envKeys);
envManager.applyOverrides(tcData.envOverrides);
}
tcData?.mockFns?.(mockAdapter);
tcData?.mockFns?.(mockAxiosFromLib);
switch (tcData.module) {
case tags.MODULES.DESTINATION:
await destinationTestHandler(tcData);
break;
case tags.MODULES.SOURCE:
FetchHandler['sourceHandlerMap'] = new Map();
tcData?.mockFns?.(mockAdapter);
tcData?.mockFns?.(mockAxiosFromLib);
await sourceTestHandler(tcData);
break;
default:
console.log('Invalid module');
// Intentionally fail the test case
expect(true).toEqual(false);
break;
}
} finally {
// Always restore environment variables after the test
if (tcData.envOverrides) {
envManager.restoreSnapshot(testId);
}
envManager.cleanup();
}
},
);
});
}
});
}
});