-
Notifications
You must be signed in to change notification settings - Fork 470
Expand file tree
/
Copy pathThreadActivityGraph.test.tsx
More file actions
589 lines (508 loc) · 20.1 KB
/
ThreadActivityGraph.test.tsx
File metadata and controls
589 lines (508 loc) · 20.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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import type {
Profile,
IndexIntoSamplesTable,
CssPixels,
} from 'firefox-profiler/types';
import { Provider } from 'react-redux';
import { render, act } from 'firefox-profiler/test/fixtures/testing-library';
import { selectedThreadSelectors } from '../../selectors/per-thread';
import { getTimelineType, getSelectedTab } from '../../selectors/url-state';
import { getLastVisibleThreadTabSlug } from '../../selectors/app';
import { ensureExists } from '../../utils/types';
import { TimelineTrackThread } from '../../components/timeline/TrackThread';
import { commitRange } from '../../actions/profile-view';
import { changeSelectedTab } from '../../actions/app';
import type {
DrawOperation,
LineToOperation,
} from '../fixtures/mocks/canvas-context';
import {
autoMockCanvasContext,
flushDrawLog,
} from '../fixtures/mocks/canvas-context';
import { mockRaf } from '../fixtures/mocks/request-animation-frame';
import { storeWithProfile } from '../fixtures/stores';
import { fireFullClick } from '../fixtures/utils';
import { getProfileFromTextSamples } from '../fixtures/profiles/processed-profile';
import {
autoMockElementSize,
setMockedElementSize,
} from '../fixtures/mocks/element-size';
import {
autoMockIntersectionObserver,
triggerIntersectionObservers,
} from '../fixtures/mocks/intersection-observer';
import { triggerResizeObservers } from '../fixtures/mocks/resize-observer';
// The following constants determine the size of the drawn graph.
const SAMPLE_COUNT = 8;
const PIXELS_PER_SAMPLE = 10;
const GRAPH_WIDTH = PIXELS_PER_SAMPLE * SAMPLE_COUNT;
const GRAPH_HEIGHT = 10;
function getSamplesPixelPosition(
sampleIndex: IndexIntoSamplesTable
): CssPixels {
// Compute the pixel position of the center of a given sample.
return sampleIndex * PIXELS_PER_SAMPLE + PIXELS_PER_SAMPLE * 0.5;
}
function getSamplesProfile() {
return getProfileFromTextSamples(`
A[cat:DOM] A[cat:DOM] A[cat:DOM] A[cat:DOM] A[cat:DOM] A[cat:DOM] A[cat:DOM] A[cat:DOM]
B B B B B B B B
C C H[cat:Layout] H[cat:Layout] H[cat:Layout] H[cat:Layout] H[cat:Layout] C
D F[cat:Graphics] I I I I I F[cat:Graphics]
E[cat:Idle] G G
`).profile;
}
describe('ThreadActivityGraph', function () {
autoMockCanvasContext();
autoMockElementSize({ width: GRAPH_WIDTH, height: GRAPH_HEIGHT });
autoMockIntersectionObserver();
function setup(profile: Profile = getSamplesProfile()) {
const store = storeWithProfile(profile);
const { getState, dispatch } = store;
const threadIndex = 0;
const flushRafCalls = mockRaf();
/**
* The ThreadActivityGraph is not a connected component. It's easiest to
* test it as once it's connected to the Redux store in TimelineTrackThread.
*/
const renderResult = render(
<Provider store={store}>
<TimelineTrackThread
threadsKey={0}
trackType="expanded"
trackName="Test Track"
/>
</Provider>
);
const { container } = renderResult;
// WithSize uses requestAnimationFrame
flushRafCalls();
const activityGraphCanvas = ensureExists(
container.querySelector('.threadActivityGraphCanvas'),
`Couldn't find the activity graph canvas, with selector .threadActivityGraphCanvas`
) as HTMLElement;
const thread = profile.threads[0];
const { funcTable, stringArray } = profile.shared;
// Perform a click on the activity graph.
function clickActivityGraph(
index: IndexIntoSamplesTable,
graphHeightPercentage: number
) {
fireFullClick(activityGraphCanvas, {
offsetX: getSamplesPixelPosition(index),
offsetY: GRAPH_HEIGHT * graphHeightPercentage,
});
}
// This function gets the selected call node path as a list of function names.
function getCallNodePath() {
return selectedThreadSelectors
.getSelectedCallNodePath(getState())
.map((funcIndex) => stringArray[funcTable.name[funcIndex]]);
}
/**
* Coordinate the flushing of the requestAnimationFrame and the draw calls.
*/
function getContextDrawCalls(): string[] {
flushRafCalls();
return (window as any).__flushDrawLog();
}
return {
...renderResult,
dispatch,
getState,
profile,
thread,
store,
threadIndex,
activityGraphCanvas,
clickActivityGraph,
getCallNodePath,
getContextDrawCalls,
};
}
it('matches the component snapshot', () => {
const { container } = setup();
expect(container.firstChild).toMatchSnapshot();
});
it('matches the 2d canvas draw snapshot', () => {
setup();
expect(flushDrawLog()).toMatchSnapshot();
});
it('redraws on resize', () => {
const { getContextDrawCalls } = setup();
// Flush out any existing draw calls.
getContextDrawCalls();
// Ensure we start out with 0.
expect(getContextDrawCalls().length).toEqual(0);
// Send out the resize with a width change.
// By changing the "fake" result of getBoundingClientRect, we ensure that
// the pure components rerender because their `width` props change.
setMockedElementSize({ width: GRAPH_WIDTH * 2, height: GRAPH_HEIGHT });
triggerResizeObservers();
const drawCalls = getContextDrawCalls();
// We want to ensure that we redraw the activity graph and not something
// else like the sample graph.
expect(drawCalls.some(([operation]) => operation === 'beginPath')).toBe(
true
);
});
it('redraws when the system theme changes', () => {
const { getContextDrawCalls } = setup();
// Flush out any existing draw calls.
getContextDrawCalls();
expect(getContextDrawCalls().length).toEqual(0);
// Simulate a theme change.
window.dispatchEvent(new CustomEvent('profiler-theme-change'));
const drawCalls = getContextDrawCalls();
expect(drawCalls.some(([operation]) => operation === 'beginPath')).toBe(
true
);
});
it('matches the 2d canvas draw snapshot with CPU values', () => {
const profile = getSamplesProfile();
profile.meta.interval = 1;
profile.meta.sampleUnits = {
time: 'ms',
eventDelay: 'ms',
threadCPUDelta: 'variable CPU cycles',
};
profile.threads[0].samples.threadCPUDelta = [
null,
400,
1000,
500,
100,
200,
800,
300,
];
const { getState } = setup(profile);
// If there are CPU values, it should be automatically defaulted to this view.
expect(getTimelineType(getState())).toBe('cpu-category');
expect(flushDrawLog()).toMatchSnapshot();
});
it('matches the 2d canvas draw snapshot with CPU values with missing samples', () => {
const profile = getSamplesProfile();
profile.meta.interval = 1;
profile.meta.sampleUnits = {
time: 'ms',
eventDelay: 'ms',
threadCPUDelta: 'variable CPU cycles',
};
profile.threads[0].samples.threadCPUDelta = [
null,
400,
1000,
500,
100,
200,
800,
300,
];
// Update the time array to create a gap between 3rd and 4th samples.
profile.threads[0].samples.time = [0, 1, 2, 7, 8, 9, 10, 11];
const { getState } = setup(profile);
// If there are CPU values, it should be automatically defaulted to this view.
expect(getTimelineType(getState())).toBe('cpu-category');
expect(flushDrawLog()).toMatchSnapshot();
});
it('matches the 2d canvas draw snapshot with only one CPU usage value', () => {
const { profile } = getProfileFromTextSamples('A B');
profile.meta.interval = 1;
profile.meta.sampleUnits = {
time: 'ms',
eventDelay: 'ms',
threadCPUDelta: 'variable CPU cycles',
};
// We need to have at least two samples to test it because the first
// threadCPUDelta is always null.
profile.threads[0].samples.threadCPUDelta = [null, 100];
const { getState, dispatch } = setup(profile);
// Commit a range that contains only the second sample.
act(() => {
dispatch(commitRange(0.1, 2.0));
});
// If there are CPU values, it should be automatically defaulted to this view.
expect(getTimelineType(getState())).toBe('cpu-category');
expect(flushDrawLog()).toMatchSnapshot();
});
it('selects the full call node path when clicked', function () {
const { clickActivityGraph, getCallNodePath } = setup();
// The full call node at this sample is:
// A -> B -> C -> F -> G
clickActivityGraph(1, 0.2);
expect(getCallNodePath()).toEqual(['A', 'B', 'C', 'F', 'G']);
// The full call node at this sample is:
// A -> B -> H -> I
clickActivityGraph(1, 0.8);
expect(getCallNodePath()).toEqual(['A', 'B', 'H', 'I']);
// There's no sample at this location.
clickActivityGraph(0, 1);
expect(getCallNodePath()).toEqual([]);
});
it('when clicking a stack while on a tab that does not show sample data, this selects the call tree panel', function () {
const { dispatch, getState, clickActivityGraph } = setup();
expect(getSelectedTab(getState())).toBe('calltree');
dispatch(changeSelectedTab('marker-chart'));
// The full call node at this sample is:
// A -> B -> C -> F -> G
clickActivityGraph(1, 0.2);
expect(getSelectedTab(getState())).toBe('calltree');
expect(getLastVisibleThreadTabSlug(getState())).toBe('calltree');
});
it('when clicking a stack while on a tab that shows sample data, it should not change the selected panel', function () {
const { dispatch, getState, clickActivityGraph } = setup();
expect(getSelectedTab(getState())).toBe('calltree');
dispatch(changeSelectedTab('flame-graph'));
// The full call node at this sample is:
// A -> B -> C -> F -> G
clickActivityGraph(1, 0.2);
expect(getSelectedTab(getState())).toBe('flame-graph');
expect(getLastVisibleThreadTabSlug(getState())).toBe('flame-graph');
});
it(`when clicking outside of the graph, this doesn't select the call tree panel`, function () {
const { dispatch, getState, clickActivityGraph } = setup();
expect(getSelectedTab(getState())).toBe('calltree');
dispatch(changeSelectedTab('marker-chart'));
// There's no sample at this location.
clickActivityGraph(0, 1);
expect(getSelectedTab(getState())).toBe('marker-chart');
expect(getLastVisibleThreadTabSlug(getState())).toBe('marker-chart');
});
it("when clicking a sample in a track with only '(root)' samples, this doesn't select the hidden call tree panel", function () {
const { profile } = getProfileFromTextSamples('(root)');
const { getState, clickActivityGraph } = setup(profile);
expect(getSelectedTab(getState())).toBe('marker-chart');
clickActivityGraph(1, 0.2);
expect(getSelectedTab(getState())).toBe('marker-chart');
});
it('will redraw even when there are no samples in range', function () {
const { dispatch } = setup();
flushDrawLog();
// Commit a thin range which contains no samples
act(() => {
dispatch(commitRange(0.5, 0.6));
});
const drawCalls = flushDrawLog();
// We use the presence of 'globalCompositeOperation' to know
// whether the canvas was redrawn or not.
expect(drawCalls.map(([fn]) => fn)).toContain(
'set globalCompositeOperation'
);
});
it('will compute the percentage properly even though it is in a committed range with missing samples', function () {
const MS_TO_NS_MULTIPLIER = 1000000;
const profile = getSamplesProfile();
profile.meta.interval = 1;
profile.meta.sampleUnits = {
time: 'ms',
eventDelay: 'ms',
threadCPUDelta: 'ns',
};
// We are creating a profile which has 8ms missing sample area in it.
// It's starting between the sample 2 and 3.
profile.threads[0].samples.threadCPUDelta = [
null,
0.4 * MS_TO_NS_MULTIPLIER,
0.1 * MS_TO_NS_MULTIPLIER,
4 * MS_TO_NS_MULTIPLIER, // It's 50% CPU because the actual interval is 8ms.
1 * MS_TO_NS_MULTIPLIER,
0.2 * MS_TO_NS_MULTIPLIER,
0.8 * MS_TO_NS_MULTIPLIER,
0.3 * MS_TO_NS_MULTIPLIER,
];
profile.threads[0].samples.time = [
0,
1,
2,
10, // For this sample, the interval is 8ms since there are missing samples.
11,
12,
13,
14,
];
const { dispatch } = setup(profile);
flushDrawLog();
// Commit a range that starts right after the missing sample.
act(() => {
dispatch(commitRange(9, 14));
});
const drawCalls = flushDrawLog();
// Activity graph uses lineTo to draw the lines for the samples.
const lineToOperations = drawCalls.filter<LineToOperation>(
// @ts-expect-error - TS2345: Signature '([operation]: DrawOperation): boolean' must be a type predicate.ts(2345)
([operation]) => operation === 'lineTo'
);
expect(lineToOperations.length).toBeGreaterThan(0);
// Make sure that all the lineTo operations are inside the activity graph
// rectangle. There should not be any sample that starts or ends outside
// of the graph.
expect(
lineToOperations.filter(
([, x, y]) =>
x < 0 ||
x > GRAPH_WIDTH ||
y < 0 ||
y > GRAPH_HEIGHT ||
isNaN(x) ||
isNaN(y)
)
).toEqual([]);
});
it('selects the correct call node path when clicked on an area where multiple stacks overlap with various categories', function () {
const { profile } = getProfileFromTextSamples(`
A[cat:DOM] A[cat:DOM] A[cat:DOM] A[cat:DOM] A[cat:DOM] A[cat:DOM] A[cat:DOM] A[cat:DOM]
B B B B B B B B
C C H H H H H C
D F I I K[cat:Layout] L J F[cat:Graphics]
E[cat:Idle] G G
`);
const { clickActivityGraph, getCallNodePath } = setup(profile);
// Previously every sample was taking 10 pixel and the graph width was
// sample count * 10. Reducing the size of the graph to make sure that we
// have multiple overlapping samples.
setMockedElementSize({ width: GRAPH_WIDTH / 4, height: GRAPH_HEIGHT });
triggerResizeObservers();
// The full call node at this sample is:
// A -> B -> H -> J
clickActivityGraph(2 / 4, 0.1);
expect(getCallNodePath()).toEqual(['A', 'B', 'H', 'J']);
// The full call node at this sample is:
// A -> B -> H -> L
clickActivityGraph(2 / 4, 0.2);
expect(getCallNodePath()).toEqual(['A', 'B', 'H', 'L']);
// The full call node at this sample is:
// A -> B -> H -> I
clickActivityGraph(2 / 4, 0.5);
expect(getCallNodePath()).toEqual(['A', 'B', 'H', 'I']);
// The full call node at this sample is:
// A -> B -> H -> K
clickActivityGraph(2 / 4, 0.8);
expect(getCallNodePath()).toEqual(['A', 'B', 'H', 'K']);
// // There's no sample at this location.
clickActivityGraph(0, 1);
expect(getCallNodePath()).toEqual([]);
});
});
describe('ThreadActivityGraph with intersection observer', function () {
// Do not automatically trigger the intersection observers.
autoMockCanvasContext();
autoMockElementSize({ width: GRAPH_WIDTH, height: GRAPH_HEIGHT });
autoMockIntersectionObserver(false);
function setup(profile: Profile = getSamplesProfile()) {
const store = storeWithProfile(profile);
const { getState, dispatch } = store;
const flushRafCalls = mockRaf();
/**
* The ThreadActivityGraph is not a connected component. It's easiest to
* test it as once it's connected to the Redux store in TimelineTrackThread.
*/
const renderResult = render(
<Provider store={store}>
<TimelineTrackThread
threadsKey={0}
trackType="expanded"
trackName="Test Track"
/>
</Provider>
);
// WithSize uses requestAnimationFrame
flushRafCalls();
/**
* Coordinate the flushing of the requestAnimationFrame and the draw calls.
*/
function getContextDrawCalls(): DrawOperation[] {
flushRafCalls();
return (window as any).__flushDrawLog();
}
return {
...renderResult,
dispatch,
getState,
profile,
store,
getContextDrawCalls,
};
}
it('will not draw before the intersection observer', () => {
const { getContextDrawCalls } = setup();
const drawCalls = getContextDrawCalls();
// There are other canvases inside the TrackThread too. We want to make sure
// that activity graph is not drawn yet.
expect(drawCalls.some(([operation]) => operation === 'beginPath')).toBe(
false
);
});
it('will not draw after the intersection observer if it is not intersecting', () => {
const { getContextDrawCalls } = setup();
let drawCalls = getContextDrawCalls();
// There are other canvases inside the TrackThread too. We want to make sure
// that activity graph is not drawn yet.
expect(drawCalls.some(([operation]) => operation === 'beginPath')).toBe(
false
);
// Now let's trigger the intersection observer and make sure that it still
// doesn't draw it.
triggerIntersectionObservers({ isIntersecting: false });
drawCalls = getContextDrawCalls();
expect(drawCalls.some(([operation]) => operation === 'beginPath')).toBe(
false
);
});
it('will draw after the intersection observer if it is intersecting', () => {
const { getContextDrawCalls } = setup();
let drawCalls = getContextDrawCalls();
// There are other canvases inside the TrackThread too. We want to make sure
// that activity graph is not drawn yet.
expect(drawCalls.some(([operation]) => operation === 'beginPath')).toBe(
false
);
// Now let's trigger the intersection observer and make sure that it draws it.
triggerIntersectionObservers({ isIntersecting: true });
drawCalls = getContextDrawCalls();
expect(drawCalls.some(([operation]) => operation === 'beginPath')).toBe(
true
);
});
it('will redraw after it becomes visible again', () => {
const { getContextDrawCalls } = setup();
let drawCalls = getContextDrawCalls();
// There are other canvases inside the TrackThread too. We want to make sure
// that activity graph is not drawn yet.
expect(drawCalls.some(([operation]) => operation === 'beginPath')).toBe(
false
);
// Now let's trigger the intersection observer and make sure that it draws it.
triggerIntersectionObservers({ isIntersecting: true });
drawCalls = getContextDrawCalls();
expect(drawCalls.some(([operation]) => operation === 'beginPath')).toBe(
true
);
// Now it goes out of view again. Make sure that we don't redraw.
triggerIntersectionObservers({ isIntersecting: false });
drawCalls = getContextDrawCalls();
expect(drawCalls.some(([operation]) => operation === 'beginPath')).toBe(
false
);
// Send out the resize with a width change.
// By changing the "fake" result of getBoundingClientRect, we ensure that
// the pure components rerender because their `width` props change.
setMockedElementSize({ width: GRAPH_WIDTH * 2, height: GRAPH_HEIGHT });
triggerResizeObservers();
drawCalls = getContextDrawCalls();
// It should still be not drawn yet.
expect(drawCalls.some(([operation]) => operation === 'beginPath')).toBe(
false
);
// Now let's trigger the intersection observer again and make sure that it redraws.
triggerIntersectionObservers({ isIntersecting: true });
drawCalls = getContextDrawCalls();
expect(drawCalls.some(([operation]) => operation === 'beginPath')).toBe(
true
);
});
});