forked from googleapis/cloud-trace-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest-cls.ts
325 lines (292 loc) · 10.6 KB
/
test-cls.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
// 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.
import * as assert from 'assert';
import {describe, it, beforeEach, afterEach} from 'mocha';
import {EventEmitter} from 'events';
import * as semver from 'semver';
import {inspect} from 'util';
import {TraceCLS, TraceCLSConfig, TraceCLSMechanism} from '../src/cls';
import {AsyncHooksCLS} from '../src/cls/async-hooks';
import {AsyncListenerCLS} from '../src/cls/async-listener';
import {CLS} from '../src/cls/base';
import {NullCLS} from '../src/cls/null';
import {SingularCLS} from '../src/cls/singular';
import {SpanType} from '../src/constants';
import {createStackTrace} from '../src/util';
import {TestLogger} from './logger';
import {plan} from './utils';
interface CLSConstructor {
new (defaultValue: string): CLS<string>;
}
describe('Continuation-Local Storage', () => {
const asyncAwaitSupported = semver.satisfies(process.version, '>=8');
describe('No-op implementation', () => {
const clazz = NullCLS;
let instance: CLS<string>;
beforeEach(() => {
instance = new clazz('default');
instance.enable();
});
afterEach(() => {
instance.disable();
});
it('always returns the default value', () => {
assert.strictEqual(instance.getContext(), 'default');
assert.strictEqual(instance.getContext(), 'default');
const result = instance.runWithContext(() => {
assert.strictEqual(instance.getContext(), 'default');
return instance.getContext();
}, 'modified');
assert.strictEqual(result, 'default');
const boundFn = instance.runWithContext(() => {
return instance.bindWithCurrentContext(() => {
assert.strictEqual(instance.getContext(), 'default');
return instance.getContext();
});
}, 'modified');
assert.strictEqual(boundFn(), 'default');
});
});
describe('Implementations', () => {
const testCases: CLSConstructor[] = asyncAwaitSupported
? [AsyncHooksCLS, AsyncListenerCLS]
: [AsyncListenerCLS];
for (const testCase of testCases) {
describe(`CLS for class ${testCase.name}`, () => {
let c!: CLS<string>;
beforeEach(() => {
c = new testCase('default');
c.enable();
});
afterEach(() => {
c.disable();
});
it('test case is default', () => {
assert.ok(c.isEnabled());
// has a default value
assert.strictEqual(c.getContext(), 'default');
});
it('Starts a new continuation with runWithContext', () => {
const result = c.runWithContext(() => {
assert.strictEqual(c.getContext(), 'modified');
return 'returned value';
}, 'modified');
assert.strictEqual(result, 'returned value');
});
// To avoid I/O we don't test context propagation over anything
// requiring opening sockets or files of any kind. The responsibility
// of testing behavior like this should fall on the context
// propagation libraries themselves.
it('Propagates context across event ticks', done => {
const progress = plan(done, 3);
c.runWithContext(() => {
process.nextTick(() => {
assert.strictEqual(c.getContext(), 'modified');
process.nextTick(() => {
assert.strictEqual(c.getContext(), 'modified');
progress();
});
});
setImmediate(() => {
assert.strictEqual(c.getContext(), 'modified');
progress();
});
setTimeout(() => {
assert.strictEqual(c.getContext(), 'modified');
progress();
}, 1);
}, 'modified');
c.runWithContext(() => {}, 'default');
});
it('Propagates context to bound functions', () => {
let runLater = () => {
assert.strictEqual(c.getContext(), 'modified');
};
c.runWithContext(() => {
runLater = c.bindWithCurrentContext(runLater);
}, 'modified');
c.runWithContext(() => {
assert.strictEqual(c.getContext(), 'default');
runLater();
assert.strictEqual(c.getContext(), 'default');
}, 'default');
c.runWithContext(() => {
// bind it again
runLater = c.bindWithCurrentContext(runLater);
}, 'modified-but-different');
runLater();
});
it('Corrects context when function run with new context throws', () => {
try {
c.runWithContext(() => {
throw new Error();
}, 'modified');
} catch (e) {
assert.strictEqual(c.getContext(), 'default');
}
});
it('Corrects context when function bound to a context throws', () => {
let runLater = () => {
throw new Error();
};
c.runWithContext(() => {
runLater = c.bindWithCurrentContext(runLater);
}, 'modified');
try {
runLater();
} catch (e) {
assert.strictEqual(c.getContext(), 'default');
}
});
it('Can be used to patch event emitters to propagate context', () => {
const ee = new EventEmitter();
assert.strictEqual(c.getContext(), 'default');
c.runWithContext(() => {
c.patchEmitterToPropagateContext(ee);
ee.on('a', () => {
assert.strictEqual(c.getContext(), 'modified');
});
}, 'modified');
c.runWithContext(() => {
// Event listeners are bound lazily.
ee.on('b', () => {
assert.strictEqual(c.getContext(), 'modified-again');
});
ee.emit('a');
assert.strictEqual(c.getContext(), 'modified-again');
}, 'modified-again');
ee.on('c', () => {
assert.strictEqual(c.getContext(), 'default');
});
ee.emit('b');
ee.emit('c');
});
it('Supports nesting contexts', done => {
c.runWithContext(() => {
c.runWithContext(() => {
setImmediate(() => {
assert.strictEqual(c.getContext(), 'inner');
done();
});
}, 'inner');
assert.strictEqual(c.getContext(), 'outer');
}, 'outer');
});
it('Supports basic context propagation across Promise#then calls', () => {
return c.runWithContext(() => {
return Promise.resolve().then(() => {
assert.strictEqual(c.getContext(), 'modified');
});
}, 'modified');
});
});
}
describe('SingularCLS', () => {
it('uses a single global context', async () => {
const cls = new SingularCLS('default');
cls.enable();
cls.runWithContext(() => {}, 'modified');
await Promise.resolve();
assert.strictEqual(cls.getContext(), 'modified');
});
});
});
describe('TraceCLS', () => {
const validTestCases: Array<{
config: TraceCLSConfig;
expectedDefaultType: SpanType;
}> = [
{
config: {mechanism: TraceCLSMechanism.ASYNC_LISTENER},
expectedDefaultType: SpanType.UNCORRELATED,
},
{
config: {mechanism: TraceCLSMechanism.SINGULAR},
expectedDefaultType: SpanType.UNCORRELATED,
},
{
config: {mechanism: TraceCLSMechanism.NONE},
expectedDefaultType: SpanType.UNCORRELATED,
},
];
if (asyncAwaitSupported) {
validTestCases.push({
config: {mechanism: TraceCLSMechanism.ASYNC_HOOKS},
expectedDefaultType: SpanType.UNCORRELATED,
});
}
for (const testCase of validTestCases) {
describe(`with configuration ${inspect(testCase)}`, () => {
const logger = new TestLogger();
let c: TraceCLS;
beforeEach(() => {
try {
c = new TraceCLS(testCase.config, logger);
c.enable();
} catch {
c = {disable: () => {}} as TraceCLS;
}
});
afterEach(() => {
c.disable();
logger.clearLogs();
});
it("when disabled, doesn't throw and has reasonable default values", () => {
c.disable();
assert.ok(!c.isEnabled());
assert.ok(c.getContext().type, SpanType.UNSAMPLED);
assert.ok(
c.runWithContext(() => 'hi', TraceCLS.UNCORRELATED),
'hi'
);
const fn = () => {};
assert.strictEqual(c.bindWithCurrentContext(fn), fn);
c.patchEmitterToPropagateContext(new EventEmitter());
});
it('confirm test case is enabled and has expected default type', () => {
assert.ok(c.isEnabled());
assert.strictEqual(c.getContext().type, testCase.expectedDefaultType);
});
it('constructs the correct underlying CLS mechanism', () => {
assert.strictEqual(
logger.getNumLogsWith('info', `[${testCase.config.mechanism}]`),
1
);
});
it('exposes the correct number of stack frames to remove', () => {
function myFunction() {
c.runWithContext(() => {
const frames = createStackTrace(1, c.rootSpanStackOffset);
assert.strictEqual(frames[0].method_name, 'myFunction');
}, TraceCLS.UNCORRELATED);
}
myFunction();
});
});
}
const invalidTestCases: TraceCLSConfig[] = asyncAwaitSupported
? // eslint-disable-next-line @typescript-eslint/no-explicit-any
[{mechanism: 'unknown'} as any]
: // eslint-disable-next-line @typescript-eslint/no-explicit-any
[{mechanism: 'unknown'} as any, {mechanism: 'async-hooks'}];
for (const testCase of invalidTestCases) {
describe(`with configuration ${inspect(testCase)}`, () => {
const logger = new TestLogger();
it('throws', () => {
assert.throws(() => new TraceCLS(testCase, logger));
});
});
}
});
});