-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathcore.ts
304 lines (272 loc) · 11.4 KB
/
core.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
// Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
import * as deepl from 'deepl-node';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { v4 as randomUUID } from 'uuid';
// Note: this constant cannot be exported immediately, because exports are locally undefined
const internalExampleText: Record<string, string> = {
ar: 'شعاع البروتون',
bg: 'протонен лъч',
cs: 'protonový paprsek',
da: 'protonstråle',
de: 'Protonenstrahl',
el: 'δέσμη πρωτονίων',
en: 'proton beam',
'en-US': 'proton beam',
'en-GB': 'proton beam',
es: 'haz de protones',
et: 'prootonikiirgus',
fi: 'protonisäde',
fr: 'faisceau de protons',
hu: 'protonnyaláb',
id: 'berkas proton',
it: 'fascio di protoni',
ja: '陽子ビーム',
ko: '양성자 빔',
lt: 'protonų spindulys',
lv: 'protonu staru kūlis',
nb: 'protonstråle',
nl: 'protonenbundel',
pl: 'wiązka protonów',
pt: 'feixe de prótons',
'pt-BR': 'feixe de prótons',
'pt-PT': 'feixe de prótons',
ro: 'fascicul de protoni',
ru: 'протонный луч',
sk: 'protónový lúč',
sl: 'protonski žarek',
sv: 'protonstråle',
tr: 'proton ışını',
uk: 'протонний пучок',
zh: '质子束',
'zh-HANS': '质子束',
'zh-HANT': '質子束',
};
export const usingMockServer = process.env.DEEPL_MOCK_SERVER_PORT !== undefined;
const usingMockProxyServer =
usingMockServer && process.env.DEEPL_MOCK_PROXY_SERVER_PORT !== undefined;
/**
* Creates a random authKey for testing purposes. Only valid if using mock-server.
*/
function randomAuthKey(): string {
if (!usingMockServer) throw new Error('A random authKey is only valid using mock-server.');
return randomUUID();
}
function makeSessionName(): string {
return `${expect.getState().currentTestName}/${randomUUID()}`;
}
export const exampleText = internalExampleText;
export const exampleDocumentInput = exampleText.en;
export const exampleDocumentOutput = exampleText.de;
export const exampleLargeDocumentInput = (exampleText.en + '\n').repeat(1000);
export const exampleLargeDocumentOutput = (exampleText.de + '\n').repeat(1000);
/**
* Creates temp directory, test files for a small and large .txt document, and an output path.
*/
export function tempFiles() {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'deepl-node-test-'));
const exampleDocument = `${tempDir}/example_document.txt`;
const exampleLargeDocument = `${tempDir}/example_large_document.txt`;
const outputDocumentPath = `${tempDir}/output_document.txt`;
fs.writeFileSync(exampleDocument, exampleDocumentInput);
fs.writeFileSync(exampleLargeDocument, exampleLargeDocumentInput);
return [exampleDocument, exampleLargeDocument, outputDocumentPath, tempDir];
}
export interface TestTranslatorOptions {
authKey?: string;
randomAuthKey?: boolean;
maxRetries?: number;
minTimeout?: number;
proxy?: deepl.ProxyConfig;
sendPlatformInfo?: boolean;
appInfo?: deepl.AppInfo;
mockServerNoResponseTimes?: number;
mockServer429ResponseTimes?: number;
mockServerInitCharacterLimit?: number;
mockServerInitDocumentLimit?: number;
mockServerInitTeamDocumentLimit?: number;
mockServerDocFailureTimes?: number;
mockServerDocQueueTime?: number;
mockServerDocTranslateTime?: number;
mockServerExpectProxy?: boolean;
mockServerOptional?: boolean;
}
/**
* Create a Translator object using given options for authKey, timeouts & retries, and mock-server
* session settings.
* @param options Options controlling Translator behaviour and mock-server sessions settings.
*/
export function makeTranslator(options?: TestTranslatorOptions): deepl.Translator {
if (!usingMockServer && process.env.DEEPL_AUTH_KEY === undefined) {
throw Error('DEEPL_AUTH_KEY environment variable must be defined unless using mock-server');
}
const authKey =
options?.authKey ||
(options?.randomAuthKey ? randomAuthKey() : process.env.DEEPL_AUTH_KEY || '');
const serverUrl = process.env.DEEPL_SERVER_URL;
const sessionHeaders: Record<string, string> = {};
if (options?.mockServerNoResponseTimes !== undefined)
sessionHeaders['mock-server-session-no-response-count'] = String(
options?.mockServerNoResponseTimes,
);
if (options?.mockServer429ResponseTimes !== undefined)
sessionHeaders['mock-server-session-429-count'] = String(
options?.mockServer429ResponseTimes,
);
if (options?.mockServerInitCharacterLimit !== undefined)
sessionHeaders['mock-server-session-init-character-limit'] = String(
options?.mockServerInitCharacterLimit,
);
if (options?.mockServerInitDocumentLimit !== undefined)
sessionHeaders['mock-server-session-init-document-limit'] = String(
options?.mockServerInitDocumentLimit,
);
if (options?.mockServerInitTeamDocumentLimit !== undefined)
sessionHeaders['mock-server-session-init-team-document-limit'] = String(
options?.mockServerInitTeamDocumentLimit,
);
if (options?.mockServerDocFailureTimes !== undefined)
sessionHeaders['mock-server-session-doc-failure'] = String(
options?.mockServerDocFailureTimes,
);
if (options?.mockServerDocQueueTime !== undefined)
sessionHeaders['mock-server-session-doc-queue-time'] = String(
options?.mockServerDocQueueTime,
);
if (options?.mockServerDocTranslateTime !== undefined)
sessionHeaders['mock-server-session-doc-translate-time'] = String(
options?.mockServerDocTranslateTime,
);
if (options?.mockServerExpectProxy !== undefined)
sessionHeaders['mock-server-session-expect-proxy'] = options?.mockServerExpectProxy
? '1'
: '0';
if (Object.entries(sessionHeaders).length !== 0) {
if (!usingMockServer && !options?.mockServerOptional)
throw new Error('Mock-server session is only used if using mock-server.');
sessionHeaders['mock-server-session'] = makeSessionName();
}
return new deepl.Translator(authKey, {
serverUrl: serverUrl,
headers: sessionHeaders,
minTimeout: options?.minTimeout,
maxRetries: options?.maxRetries,
proxy: options?.proxy,
sendPlatformInfo: options?.sendPlatformInfo,
appInfo: options?.appInfo,
});
}
/**
* Create a Translator object using given options for authKey, timeouts & retries, and mock-server
* session settings.
* @param options Options controlling Translator behaviour and mock-server sessions settings.
*/
export function makeDeeplClient(options?: TestTranslatorOptions): deepl.DeepLClient {
if (!usingMockServer && process.env.DEEPL_AUTH_KEY === undefined) {
throw Error('DEEPL_AUTH_KEY environment variable must be defined unless using mock-server');
}
const authKey =
options?.authKey ||
(options?.randomAuthKey ? randomAuthKey() : process.env.DEEPL_AUTH_KEY || '');
const serverUrl = process.env.DEEPL_SERVER_URL;
const sessionHeaders: Record<string, string> = {};
if (options?.mockServerNoResponseTimes !== undefined)
sessionHeaders['mock-server-session-no-response-count'] = String(
options?.mockServerNoResponseTimes,
);
if (options?.mockServer429ResponseTimes !== undefined)
sessionHeaders['mock-server-session-429-count'] = String(
options?.mockServer429ResponseTimes,
);
if (options?.mockServerInitCharacterLimit !== undefined)
sessionHeaders['mock-server-session-init-character-limit'] = String(
options?.mockServerInitCharacterLimit,
);
if (options?.mockServerInitDocumentLimit !== undefined)
sessionHeaders['mock-server-session-init-document-limit'] = String(
options?.mockServerInitDocumentLimit,
);
if (options?.mockServerInitTeamDocumentLimit !== undefined)
sessionHeaders['mock-server-session-init-team-document-limit'] = String(
options?.mockServerInitTeamDocumentLimit,
);
if (options?.mockServerDocFailureTimes !== undefined)
sessionHeaders['mock-server-session-doc-failure'] = String(
options?.mockServerDocFailureTimes,
);
if (options?.mockServerDocQueueTime !== undefined)
sessionHeaders['mock-server-session-doc-queue-time'] = String(
options?.mockServerDocQueueTime,
);
if (options?.mockServerDocTranslateTime !== undefined)
sessionHeaders['mock-server-session-doc-translate-time'] = String(
options?.mockServerDocTranslateTime,
);
if (options?.mockServerExpectProxy !== undefined)
sessionHeaders['mock-server-session-expect-proxy'] = options?.mockServerExpectProxy
? '1'
: '0';
if (Object.entries(sessionHeaders).length !== 0) {
if (!usingMockServer && !options?.mockServerOptional)
throw new Error('Mock-server session is only used if using mock-server.');
sessionHeaders['mock-server-session'] = makeSessionName();
}
return new deepl.DeepLClient(authKey, {
serverUrl: serverUrl,
headers: sessionHeaders,
minTimeout: options?.minTimeout,
maxRetries: options?.maxRetries,
proxy: options?.proxy,
sendPlatformInfo: options?.sendPlatformInfo,
appInfo: options?.appInfo,
});
}
// Use instead of it(...) for tests that require a mock-server
export const withMockServer = usingMockServer ? it : it.skip;
// Use instead of it(...) for tests that require a mock-server with proxy
export const withMockProxyServer = usingMockProxyServer ? it : it.skip;
// Use instead of it(...) for tests that cannot run using mock-server
export const withRealServer = usingMockServer ? it.skip : it;
const proxyUrlString = process.env.DEEPL_PROXY_URL;
const proxyUrl = proxyUrlString ? new URL(proxyUrlString) : undefined;
const proxyConfigHost = proxyUrl ? proxyUrl.hostname : '';
const proxyConfigPort = parseInt(process.env.DEEPL_MOCK_PROXY_SERVER_PORT || '');
export const proxyConfig: deepl.ProxyConfig = { host: proxyConfigHost, port: proxyConfigPort };
// Wrap setTimeout() with Promise
export const timeout = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
// Mocked document translation tests need slightly higher timeout limit
export const documentTranslationTestTimeout = 10000;
// E2E tests need a significantly higher timeout limit
export const testTimeout = 60000;
// Base URL for mocking out HTTP client
export const urlToMockRegexp =
/(https?:\/\/api.*\.deepl\.com)|(deepl-mock:\d+)|(https?:\/\/localhost:\d+)/;
// For Document Minification
export const testFilePaths = {
pptx: 'tests/resources/example_presentation_template.pptx',
docx: 'tests/resources/example_document_template.docx',
zip: 'tests/resources/example_zip_template.zip',
};
module.exports = {
testFilePaths,
exampleText,
exampleDocumentInput,
exampleDocumentOutput,
exampleLargeDocumentInput,
exampleLargeDocumentOutput,
tempFiles,
withMockServer,
withMockProxyServer,
withRealServer,
makeTranslator,
makeDeeplClient,
documentTranslationTestTimeout,
testTimeout,
timeout,
urlToMockRegexp,
proxyConfig,
usingMockServer,
};