-
Notifications
You must be signed in to change notification settings - Fork 470
Expand file tree
/
Copy pathStackChart.test.tsx
More file actions
671 lines (564 loc) · 20 KB
/
StackChart.test.tsx
File metadata and controls
671 lines (564 loc) · 20 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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
/* 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 { Provider } from 'react-redux';
import {
render,
fireEvent,
screen,
act,
within,
} from 'firefox-profiler/test/fixtures/testing-library';
import * as UrlStateSelectors from '../../selectors/url-state';
import * as ProfileSelectors from '../../selectors/profile';
// This module is mocked.
import copy from 'copy-to-clipboard';
import {
TIMELINE_MARGIN_LEFT,
TIMELINE_MARGIN_RIGHT,
} from '../../app-logic/constants';
import { StackChart } from '../../components/stack-chart';
import { CallNodeContextMenu } from '../../components/shared/CallNodeContextMenu';
import {
getEmptyThread,
getEmptyProfile,
} from '../../profile-logic/data-structures';
import {
changeSelectedCallNode,
commitRange,
changeImplementationFilter,
changeCallTreeSummaryStrategy,
updatePreviewSelection,
changeCallTreeSearchString,
} from '../../actions/profile-view';
import { changeSelectedTab } from '../../actions/app';
import { selectedThreadSelectors } from '../../selectors/per-thread';
import { ensureExists } from '../../utils/types';
import {
autoMockCanvasContext,
flushDrawLog,
} from '../fixtures/mocks/canvas-context';
import { mockRaf } from '../fixtures/mocks/request-animation-frame';
import { storeWithProfile } from '../fixtures/stores';
import type { FakeMouseEventInit } from '../fixtures/utils';
import {
getMouseEvent,
addRootOverlayElement,
removeRootOverlayElement,
findFillTextPositionFromDrawLog,
fireFullClick,
fireFullContextMenu,
fireFullKeyPress,
} from '../fixtures/utils';
import {
getProfileFromTextSamples,
getProfileWithMarkers,
getUserTiming,
getProfileWithJsAllocations,
} from '../fixtures/profiles/processed-profile';
import { autoMockElementSize } from '../fixtures/mocks/element-size';
import type { CssPixels, Store } from 'firefox-profiler/types';
import { unserializeProfileOfArbitraryFormat } from 'firefox-profiler/profile-logic/process-profile';
jest.useFakeTimers();
const GRAPH_BASE_WIDTH = 200;
const GRAPH_WIDTH =
GRAPH_BASE_WIDTH + TIMELINE_MARGIN_LEFT + TIMELINE_MARGIN_RIGHT;
const GRAPH_HEIGHT = 300;
autoMockCanvasContext();
autoMockElementSize({ width: GRAPH_WIDTH, height: GRAPH_HEIGHT });
beforeEach(addRootOverlayElement);
afterEach(removeRootOverlayElement);
describe('StackChart', function () {
it('matches the snapshot and can display a tooltip', () => {
const { container, getTooltip, moveMouse } = setupSamples();
const drawCalls = flushDrawLog();
expect(container.firstChild).toMatchSnapshot('dom');
expect(drawCalls).toMatchSnapshot('draw calls');
// It can also display a tooltip when hovering a stack.
expect(getTooltip()).toBe(null);
moveMouse(findFillTextPositionFromDrawLog(drawCalls, 'B'));
expect(getTooltip()).toBeTruthy();
expect(getTooltip()).toMatchSnapshot('tooltip');
});
it('matches the snapshot and can display a tooltip with the same widths option', () => {
const samples = `
A[cat:DOM] A[cat:DOM] A[cat:DOM] A[cat:DOM]
B[cat:DOM] B[cat:DOM] B[cat:DOM] B[cat:DOM]
C[cat:Graphics] C[cat:Graphics] C[cat:Graphics] H[cat:Network]
D[cat:Graphics] F[cat:Graphics] F[cat:Graphics] I[cat:Network]
E[cat:Graphics] G[cat:Graphics] G[cat:Graphics]
`;
const { getTooltip, moveMouse, flushRafCalls, dispatch } =
setupSamples(samples);
useSameWidthsStackChart({ flushRafCalls });
let drawCalls = flushDrawLog();
expect(document.body).toMatchSnapshot('dom');
expect(getDrawnFrames(drawCalls)).toEqual([
'A',
'B',
'C',
'H',
'D',
'F',
'I',
'E',
'G',
]);
expect(drawCalls).toMatchSnapshot('draw calls');
// It can also display a tooltip when hovering a stack.
expect(getTooltip()).toBe(null);
moveMouse(findFillTextPositionFromDrawLog(drawCalls, 'I'));
expect(getTooltip()).toBeTruthy();
expect(getTooltip()).toMatchSnapshot('tooltip');
// Let's add a preview selection and do it again.
flushDrawLog();
act(() =>
dispatch(
updatePreviewSelection({
isModifying: false,
selectionStart: 3.1,
selectionEnd: 3.4,
})
)
);
flushRafCalls();
drawCalls = flushDrawLog();
expect(getDrawnFrames(drawCalls)).toEqual([
'A',
'B',
'C',
'H',
'F',
'I',
'G',
]);
expect(drawCalls).toMatchSnapshot('draw calls for preview selection');
// It can also display a tooltip when hovering a new stack.
moveMouse(findFillTextPositionFromDrawLog(drawCalls, 'H'));
expect(getTooltip()).toBeTruthy();
expect(getTooltip()).toMatchSnapshot('tooltip after preview selection');
});
it('can select a call node when clicking the chart', function () {
const { dispatch, getState, leftClick, findFillTextPosition } =
setupSamples();
// Start out deselected
act(() => {
dispatch(changeSelectedCallNode(0, []));
});
expect(selectedThreadSelectors.getSelectedCallNodeIndex(getState())).toBe(
null
);
const { x, y } = findFillTextPosition('A');
const callNodeAIndex = 0;
// Click on function A's box.
leftClick({ x, y });
expect(selectedThreadSelectors.getSelectedCallNodeIndex(getState())).toBe(
callNodeAIndex
);
// Click on a region without any drawn box to deselect.
leftClick({ x, y: y + GRAPH_HEIGHT });
expect(selectedThreadSelectors.getSelectedCallNodeIndex(getState())).toBe(
null
);
});
it('can display the source view when pressing enter on the chart', function () {
const sourceViewFile =
'git:github.com/rust-lang/rust:library/std/src/sys/unix/thread.rs:53cb7b09b00cbea8754ffb78e7e3cb521cb8af4b';
const { dispatch, funcNames, getState, stackChartCanvas } = setupSamples(
`A[file:${sourceViewFile}]`
);
act(() => {
dispatch(changeSelectedCallNode(0, [funcNames.indexOf('A')]));
});
expect(UrlStateSelectors.getSourceViewSourceIndex(getState())).toBeNull();
fireFullKeyPress(stackChartCanvas, { key: 'Enter' });
expect(
UrlStateSelectors.getSourceViewSourceIndex(getState())
).not.toBeNull();
expect(ProfileSelectors.getSourceViewFile(getState())).toBe(sourceViewFile);
});
it('can display a context menu when right clicking the chart', function () {
// Fake timers are indicated when dealing with the context menus.
jest.useFakeTimers();
const { rightClick, getContextMenu, clickMenuItem, findFillTextPosition } =
setupSamples();
rightClick(findFillTextPosition('A'));
expect(getContextMenu()).toHaveClass('react-contextmenu--visible');
clickMenuItem('Copy function name');
expect(copy).toHaveBeenLastCalledWith('A');
// The menu should be closed now.
expect(getContextMenu()).not.toHaveClass('react-contextmenu--visible');
// Run the timers to have a clean state.
act(() => jest.runAllTimers());
// Try another to make sure the menu works for other stacks too.
rightClick(findFillTextPosition('B'));
expect(getContextMenu()).toHaveClass('react-contextmenu--visible');
clickMenuItem('Copy function name');
expect(copy).toHaveBeenLastCalledWith('B');
});
it('can scroll into view when selecting a node', function () {
// Create a stack deep enough to not have all its rendered frames
// fit within GRAPH_HEIGHT.
const frames = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'.split(
' '
);
const { dispatch, funcNames, flushRafCalls } = setupSamples(
frames.join('\n')
);
flushDrawLog();
// Select the last frame, 'Z', and then make sure we can "see" the
// drawn 'Z', but not 'A'.
act(() => {
dispatch(
changeSelectedCallNode(
0,
frames.map((name) => funcNames.indexOf(name))
)
);
});
flushRafCalls();
let drawnFrames = getDrawnFrames();
expect(drawnFrames).toContain('Z');
expect(drawnFrames).not.toContain('A');
// Now select the first frame, 'A', and check that we also can
// scroll up again and see 'A', but not 'Z'.
act(() => {
dispatch(changeSelectedCallNode(0, [funcNames.indexOf('A')]));
});
flushRafCalls();
drawnFrames = getDrawnFrames();
expect(drawnFrames).toContain('A');
expect(drawnFrames).not.toContain('Z');
});
it('dims non-matching boxes when searching', function () {
const { dispatch, flushRafCalls } = setupSamples();
flushDrawLog();
// Dispatch a search string that matches some function names.
act(() => {
dispatch(changeCallTreeSearchString('B'));
});
flushRafCalls();
const drawCalls = flushDrawLog();
// Non-matching boxes should be drawn with the dimmed style.
const dimmedFillCalls = drawCalls.filter(
([fn, value]) => fn === 'set fillStyle' && value === '#f9f9fa'
);
expect(dimmedFillCalls.length).toBeGreaterThan(0);
});
it('does not dim boxes that match the search string', function () {
// Use a single-node call stack so there is exactly one box.
const { dispatch, flushRafCalls } = setupSamples(`
A[cat:DOM]
`);
flushDrawLog();
// Search for "A" — the only node matches, so nothing should be dimmed.
act(() => {
dispatch(changeCallTreeSearchString('A'));
});
flushRafCalls();
const drawCalls = flushDrawLog();
const dimmedFillCalls = drawCalls.filter(
([fn, value]) => fn === 'set fillStyle' && value === '#f9f9fa'
);
expect(dimmedFillCalls).toHaveLength(0);
});
it('does not dim any boxes when there is no search string', function () {
setupSamples();
const drawCalls = flushDrawLog();
// No dimmed fill should be applied without a search.
const dimmedFillCalls = drawCalls.filter(
([fn, value]) => fn === 'set fillStyle' && value === '#f9f9fa'
);
expect(dimmedFillCalls).toHaveLength(0);
});
describe('EmptyReasons', () => {
it('shows reasons when a profile has no samples', () => {
const profile = getEmptyProfile();
const thread = getEmptyThread();
thread.name = 'Empty Thread';
profile.threads.push(thread);
const store = storeWithProfile(profile);
const container = render(
<Provider store={store}>
<>
<StackChart />
</>
</Provider>
).container;
expect(container.querySelector('.EmptyReasons')).toMatchSnapshot();
});
it('shows reasons when samples are out of range', () => {
const { dispatch, container } = setupSamples();
act(() => {
dispatch(commitRange(5, 10));
});
expect(container.querySelector('.EmptyReasons')).toMatchSnapshot();
});
it('shows reasons when samples have been completely filtered out', function () {
const { dispatch, container } = setupSamples();
act(() => {
dispatch(changeImplementationFilter('js'));
});
expect(container.querySelector('.EmptyReasons')).toMatchSnapshot();
});
});
it('works when the user selects the JS allocations option', function () {
setupAllocations();
const drawCalls = flushDrawLog();
expect(document.body).toMatchSnapshot();
expect(drawCalls).toMatchSnapshot();
});
});
describe('ArgumentValues', () => {
it('shows argument values when a profile has them', async () => {
const profiler = await unserializeProfileOfArbitraryFormat(
require('../fixtures/upgrades/argument-values.json')
);
const store = storeWithProfile(profiler);
const { getTooltip, moveMouse, findFillTextPosition } = setup(store);
moveMouse(findFillTextPosition('bar'));
const tooltip = getTooltip();
expect(within(ensureExists(tooltip)).getByText('bar')).toBeInTheDocument();
expect(tooltip).toMatchSnapshot();
});
});
describe('MarkerChart', function () {
it('can turn on the show user timings', () => {
const { getByLabelText, getState } = setupUserTimings({
isShowUserTimingsClicked: false,
});
const checkbox = getByLabelText('Show user timing') as HTMLElement;
expect(UrlStateSelectors.getShowUserTimings(getState())).toBe(false);
expect(getCheckedState(checkbox)).toBe(false);
fireFullClick(checkbox);
expect(UrlStateSelectors.getShowUserTimings(getState())).toBe(true);
expect(getCheckedState(checkbox)).toBe(true);
});
it('matches the snapshots for the component and draw log', () => {
const { container } = setupUserTimings({
isShowUserTimingsClicked: true,
});
expect(container.firstChild).toMatchSnapshot();
expect(flushDrawLog()).toMatchSnapshot();
});
// TODO implement selecting user timing markers #2355
it.todo('can select a marker when clicking the chart');
// TODO implement selecting user timing markers #2355
it.todo('can right click a marker and show a context menu');
it('shows a tooltip when hovering', () => {
const { getTooltip, moveMouse, findFillTextPosition, flushRafCalls } =
setupUserTimings({
isShowUserTimingsClicked: true,
});
expect(getTooltip()).toBe(null);
moveMouse(findFillTextPosition('componentB'));
let tooltip = getTooltip();
expect(
within(ensureExists(tooltip)).getByText('componentB')
).toBeInTheDocument();
expect(tooltip).toMatchSnapshot();
// This still matches markers with the same widths option
useSameWidthsStackChart({ flushRafCalls });
moveMouse(findFillTextPosition('componentA'));
tooltip = getTooltip();
expect(
within(ensureExists(tooltip)).getByText('componentA')
).toBeInTheDocument();
expect(tooltip).toMatchSnapshot();
});
});
describe('CombinedChart', function () {
it('renders combined stack chart', () => {
const { container } = setupCombinedTimings();
expect(container.firstChild).toMatchSnapshot();
expect(flushDrawLog()).toMatchSnapshot();
});
});
function showUserTimings({ getByLabelText, flushRafCalls }: Setup) {
flushDrawLog();
const checkbox = getByLabelText('Show user timing') as HTMLElement;
fireFullClick(checkbox);
flushRafCalls();
}
function useSameWidthsStackChart({
flushRafCalls,
}: Pick<Setup, 'flushRafCalls'>) {
flushDrawLog();
const checkbox = screen.getByLabelText(
'Use the same width for each stack'
) as HTMLElement;
fireFullClick(checkbox);
flushRafCalls();
}
function getDrawnFrames(drawCalls = flushDrawLog()) {
return drawCalls.filter(([fn]) => fn === 'fillText').map(([, arg]) => arg);
}
function setupCombinedTimings() {
const userTimingsProfile = getProfileWithMarkers([
getUserTiming('renderFunction', 0, 10),
getUserTiming('componentA', 1, 8),
getUserTiming('componentB', 2, 4),
getUserTiming('componentC', 3, 1),
getUserTiming('componentD', 7, 1),
]);
const { profile } = getProfileFromTextSamples(`
A[cat:DOM] A[cat:DOM] A[cat:DOM]
B[cat:DOM] B[cat:DOM] B[cat:DOM]
C[cat:Graphics] C[cat:Graphics] H[cat:Network]
D[cat:Graphics] F[cat:Graphics] I[cat:Network]
E[cat:Graphics] G[cat:Graphics]
`);
profile.threads[0].markers = userTimingsProfile.threads[0].markers;
const results = setup(storeWithProfile(profile));
showUserTimings(results);
return results;
}
function setupUserTimings(config: { isShowUserTimingsClicked: boolean }) {
// Approximately generate this type of graph with the following user timings.
//
// [renderFunction---------------------]
// [componentA---------------------]
// [componentB----] [componentD]
// [componentC-]
const profile = getProfileWithMarkers([
getUserTiming('renderFunction', 0, 10),
getUserTiming('componentA', 1, 8),
getUserTiming('componentB', 2, 4),
getUserTiming('componentC', 3, 1),
getUserTiming('componentD', 7, 1),
]);
const results = setup(storeWithProfile(profile));
if (config.isShowUserTimingsClicked) {
showUserTimings(results);
}
return results;
}
/**
* Currently the stack chart only accepts samples, but in the future it will accept
* markers, see PR #2345.
*/
function setupSamples(
samples: string = `
A[cat:DOM] A[cat:DOM] A[cat:DOM]
B[cat:DOM] B[cat:DOM] B[cat:DOM]
C[cat:Graphics] C[cat:Graphics] H[cat:Network]
D[cat:Graphics] F[cat:Graphics] I[cat:Network]
E[cat:Graphics] G[cat:Graphics]
`
): Setup {
const {
profile,
funcNamesPerThread: [funcNames],
} = getProfileFromTextSamples(samples);
return setup(storeWithProfile(profile), funcNames);
}
function setupAllocations() {
const { profile, funcNames } = getProfileWithJsAllocations();
const store = storeWithProfile(profile);
store.dispatch(changeCallTreeSummaryStrategy('js-allocations'));
return setup(store, funcNames);
}
type Setup = ReturnType<typeof setup>;
/**
* Setup the stack chart component with a profile.
*/
function setup(store: Store, funcNames: string[] = []) {
const flushRafCalls = mockRaf();
store.dispatch(changeSelectedTab('stack-chart'));
const renderResult = render(
<Provider store={store}>
<>
<CallNodeContextMenu />
<StackChart />
</>
</Provider>
);
const { container } = renderResult;
flushRafCalls();
const stackChartCanvas = ensureExists(
container.querySelector('.chartCanvas.stackChartCanvas'),
`Couldn't find the stack chart canvas, with selector .chartCanvas.stackChartCanvas`
) as HTMLElement;
// Mouse event tools
function getPositioningOptions({ x, y }: { x: number; y: number }) {
// These positioning options will be sent to all our mouse events. Note
// that the values aren't really consistent, especially offsetY and
// pageY shouldn't be the same, but in the context of our test this will
// be good enough.
// pageX/Y values control the position of the tooltip so it's not super
// important.
// offsetX/Y are more important as they're used to find which node is
// actually clicked.
// clientX/Y is used in the Viewport HOC when dragging and zooming.
const positioningOptions = {
offsetX: x,
offsetY: y,
clientX: x,
clientY: y,
pageX: x,
pageY: y,
};
return positioningOptions;
}
function fireMouseEvent(eventName: string, options: FakeMouseEventInit) {
fireEvent(stackChartCanvas, getMouseEvent(eventName, options));
}
/**
* The tooltip is in a portal, and created in the root overlay elements.
*/
function getTooltip(): HTMLElement | null {
return document.querySelector(
'#root-overlay .tooltip'
) as HTMLElement | null;
}
type Position = { x: CssPixels; y: CssPixels };
// Use findFillTextPosition to determin the position.
function leftClick(where: Position) {
const positioningOptions = getPositioningOptions(where);
fireMouseEvent('mousemove', positioningOptions);
fireFullClick(stackChartCanvas, positioningOptions);
flushRafCalls();
}
function rightClick(where: Position) {
const positioningOptions = getPositioningOptions(where);
fireMouseEvent('mousemove', positioningOptions);
fireFullContextMenu(stackChartCanvas, positioningOptions);
flushRafCalls();
}
function moveMouse(where: Position) {
fireMouseEvent('mousemove', getPositioningOptions(where));
flushRafCalls();
}
// Context menu tools
const getContextMenu = () =>
ensureExists(
container.querySelector('.react-contextmenu'),
`Couldn't find the context menu.`
) as HTMLElement;
function clickMenuItem(strOrRegexp: string | RegExp) {
fireFullClick(screen.getByText(strOrRegexp));
}
function findFillTextPosition(fillText: string): Position {
return findFillTextPositionFromDrawLog(flushDrawLog(), fillText);
}
return {
...renderResult,
...store,
funcNames,
flushRafCalls,
stackChartCanvas,
moveMouse,
leftClick,
rightClick,
clickMenuItem,
getContextMenu,
getTooltip,
findFillTextPosition,
};
}
/**
* Get around the type constraints of refining an HTMLElement into a radio input.
*/
function getCheckedState(element: HTMLElement): unknown {
return (element as any).checked;
}