forked from googleapis/cloud-trace-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest-plugin-loader.ts
316 lines (283 loc) · 11.1 KB
/
test-plugin-loader.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
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* eslint-disable @typescript-eslint/no-var-requires */
import * as assert from 'assert';
import {describe, it, before, afterEach} from 'mocha';
import {
PluginLoader,
PluginLoaderState,
PluginWrapper,
} from '../src/trace-plugin-loader';
import {alwaysTrace} from '../src/tracing-policy';
import {TestLogger} from './logger';
import {getBaseConfig, NoPropagation} from './utils';
export interface SimplePluginLoaderConfig {
// An object which contains paths to files that should be loaded as plugins
// upon loading a module with a given name.
plugins: {[pluginName: string]: string};
}
const SEARCH_PATH = `${__dirname}/fixtures/loader/node_modules`;
const PROCESS_VERSION = process.version.slice(1);
const clearRequireCache = () => {
Object.keys(require.cache).forEach(key => delete require.cache[key]);
};
describe('Trace Plugin Loader', () => {
let logger: TestLogger;
const makePluginLoader = (config: SimplePluginLoaderConfig) => {
return new PluginLoader(
Object.assign({tracerConfig: getBaseConfig()}, config),
{tracePolicy: alwaysTrace(), logger, propagation: new NoPropagation()}
);
};
before(() => {
module.paths.push(SEARCH_PATH);
PluginLoader.setPluginSearchPathForTestingOnly(SEARCH_PATH);
logger = new TestLogger();
});
afterEach(() => {
logger.clearLogs();
clearRequireCache();
});
describe('interface', () => {
describe('state', () => {
it('returns NO_HOOK when first called', () => {
const pluginLoader = makePluginLoader({plugins: {}});
assert.strictEqual(pluginLoader.state, PluginLoaderState.NO_HOOK);
});
});
describe('activate', () => {
it('transitions from NO_HOOK to ACTIVATED, enabling require hook', () => {
let requireHookCalled = false;
const pluginLoader = makePluginLoader({plugins: {}});
// TODO(kjin): Stop using index properties.
pluginLoader['enableRequireHook'] = () => (requireHookCalled = true);
pluginLoader.activate();
assert.strictEqual(pluginLoader.state, PluginLoaderState.ACTIVATED);
assert.ok(requireHookCalled);
});
it('throws if internal state is already ACTIVATED', () => {
let requireHookCalled = false;
const pluginLoader = makePluginLoader({plugins: {}}).activate();
assert.strictEqual(pluginLoader.state, PluginLoaderState.ACTIVATED);
// TODO(kjin): Stop using index properties.
pluginLoader['enableRequireHook'] = () => (requireHookCalled = true);
assert.throws(() => pluginLoader.activate());
assert.ok(!requireHookCalled);
});
it('throws if internal state is DEACTIVATED', () => {
// There is currently no reason to transition back and forth.
// This behavior may change in the future.
let requireHookCalled = false;
const pluginLoader = makePluginLoader({plugins: {}})
.activate()
.deactivate();
assert.strictEqual(pluginLoader.state, PluginLoaderState.DEACTIVATED);
// TODO(kjin): Stop using index properties.
pluginLoader['enableRequireHook'] = () => (requireHookCalled = true);
assert.throws(() => pluginLoader.activate());
assert.ok(!requireHookCalled);
});
});
describe('deactivate', () => {
class TestPluginWrapper implements PluginWrapper {
unapplyCalled = false;
isSupported(): boolean {
return false;
}
unapplyAll(): void {
this.unapplyCalled = true;
}
applyPlugin<T>(moduleExports: T): T {
return moduleExports;
}
}
it('transitions state from ACTIVATED to DEACTIVATED, unapplying plugins', () => {
const pluginLoader = makePluginLoader({plugins: {}}).activate();
assert.strictEqual(pluginLoader.state, PluginLoaderState.ACTIVATED);
const plugin = new TestPluginWrapper();
// TODO(kjin): Stop using index properties.
pluginLoader['pluginMap'].set('foo', plugin);
pluginLoader.deactivate();
assert.strictEqual(pluginLoader.state, PluginLoaderState.DEACTIVATED);
assert.ok(plugin.unapplyCalled);
});
});
});
describe('static interface', () => {
describe('parseModuleString', () => {
it('parses module strings', () => {
const p = PluginLoader.parseModuleString;
assert.deepStrictEqual(p('m'), {name: 'm', file: ''});
assert.deepStrictEqual(p('m/f'), {name: 'm', file: 'f'});
assert.deepStrictEqual(p('m/d/f'), {name: 'm', file: 'd/f'});
assert.deepStrictEqual(p('m\\d\\f'), {name: 'm', file: 'd/f'});
assert.deepStrictEqual(p('@o\\m\\d\\f'), {name: '@o/m', file: 'd/f'});
assert.deepStrictEqual(p('@o/m/d/f'), {name: '@o/m', file: 'd/f'});
assert.deepStrictEqual(p('@o/m/d/f'), {name: '@o/m', file: 'd/f'});
});
});
});
describe('patching behavior', () => {
it('ensures that module fixtures contain the right values', () => {
// Ensure that module fixtures contain values that we expect.
assert.strictEqual(require('small-number').value, 0);
assert.strictEqual(require('large-number'), 1e100);
assert.strictEqual(require('my-version-1.0'), '1.0.0');
assert.strictEqual(require('my-version-1.0-pre'), '1.0.0-pre');
assert.strictEqual(require('my-version-1.1'), '1.1.0');
assert.strictEqual(require('my-version-2.0'), '2.0.0');
});
it("doesn't patch before activation", () => {
const loader = makePluginLoader({
plugins: {'small-number': 'plugin-small-number'},
});
assert.strictEqual(require('small-number').value, 0);
loader.deactivate();
});
it("doesn't patch modules for which plugins aren't specified", () => {
const loader = makePluginLoader({plugins: {}}).activate();
assert.strictEqual(require('small-number').value, 0);
loader.deactivate();
});
it('patches modules when activated, with no plugin file field specifying the main file', () => {
const loader = makePluginLoader({
plugins: {'small-number': 'plugin-small-number'},
}).activate();
assert.strictEqual(require('small-number').value, 1);
// Make sure requiring doesn't patch twice
assert.strictEqual(require('small-number').value, 1);
assert.strictEqual(
logger.getNumLogsWith('info', '[small-number@0.0.1]'),
1
);
loader.deactivate();
});
it('accepts absolute paths in configuration', () => {
const loader = makePluginLoader({
plugins: {'small-number': `${SEARCH_PATH}/plugin-small-number`},
}).activate();
assert.strictEqual(require('small-number').value, 1);
assert.strictEqual(
logger.getNumLogsWith('info', '[small-number@0.0.1]'),
1
);
loader.deactivate();
});
it('unpatches modules when deactivated', () => {
const loader = makePluginLoader({
plugins: {'small-number': 'plugin-small-number'},
}).activate();
require('small-number');
loader.deactivate();
assert.strictEqual(require('small-number').value, 0);
// One each for activate/deactivate
assert.strictEqual(
logger.getNumLogsWith('info', '[small-number@0.0.1]'),
2
);
});
it('intercepts and patches internal files', () => {
const loader = makePluginLoader({
plugins: {'large-number': 'plugin-large-number'},
}).activate();
assert.strictEqual(require('large-number'), 2e100);
loader.deactivate();
});
['http', 'url', '[core]'].forEach(key => {
it(`intercepts and patches core modules with key "${key}"`, () => {
const loader = makePluginLoader({
plugins: {[key]: 'plugin-core'},
}).activate();
const input = {protocol: 'http:', host: 'hi'};
assert.strictEqual(require('url').format(input), 'patched-value');
loader.deactivate();
assert.strictEqual(require('url').format(input), 'http://hi');
// One each for activate/deactivate
assert.strictEqual(
logger.getNumLogsWith('info', `[${key}@${PROCESS_VERSION}:url]`),
2
);
});
});
it("doesn't load plugins with falsey paths", () => {
const loader = makePluginLoader({
plugins: {'small-number': ''},
}).activate();
assert.strictEqual(require('small-number').value, 0);
loader.deactivate();
});
it('uses version ranges to determine how to patch internals', () => {
const loader = makePluginLoader({
plugins: {'my-version': 'plugin-my-version-1'},
}).activate();
assert.strictEqual(require('my-version-1.0'), '1.0.0-patched');
// v1.1 has different internals.
assert.strictEqual(require('my-version-1.1'), '1.1.0-patched');
assert.strictEqual(require('my-version-2.0'), '2.0.0');
// warns for my-version-2.0 that nothing matches
assert.strictEqual(
logger.getNumLogsWith('warn', '[my-version@2.0.0]'),
1
);
loader.deactivate();
});
it('patches pre-releases, but warns', () => {
const loader = makePluginLoader({
plugins: {'my-version': 'plugin-my-version-1'},
}).activate();
assert.strictEqual(require('my-version-1.0-pre'), '1.0.0-pre-patched');
assert.strictEqual(
logger.getNumLogsWith('warn', '[my-version@1.0.0-pre]'),
1
);
loader.deactivate();
});
it('throws when the plugin throws', () => {
const loader = makePluginLoader({
plugins: {'my-version': 'plugin-my-version-2'},
}).activate();
let threw = false;
try {
require('my-version-1.0');
} catch (e) {
threw = true;
}
assert.ok(threw);
loader.deactivate();
});
it('warns when a module is patched by a non-conformant plugin', () => {
const loader = makePluginLoader({
plugins: {'[core]': 'plugin-core'},
}).activate();
// Reasons for possible warnings issued are listed as comments.
require('crypto'); // neither patch nor intercept
require('os'); // both patch and intercept
require('dns'); // two Patch objects for a single file
// Do not warn when there is no patch/intercept function.
assert.strictEqual(
logger.getNumLogsWith('warn', `[[core]@${PROCESS_VERSION}:crypto]`),
0
);
assert.strictEqual(
logger.getNumLogsWith('warn', `[[core]@${PROCESS_VERSION}:os]`),
1
);
assert.strictEqual(
logger.getNumLogsWith('warn', `[[core]@${PROCESS_VERSION}:dns]`),
1
);
loader.deactivate();
});
});
});