forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackChart.test.js
486 lines (404 loc) · 14 KB
/
StackChart.test.js
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
/* 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/. */
// @flow
import * as React from 'react';
import { Provider } from 'react-redux';
import {
render,
fireEvent,
screen,
act,
} from 'firefox-profiler/test/fixtures/testing-library';
import * as UrlStateSelectors from '../../selectors/url-state';
// 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,
} from '../../actions/profile-view';
import { changeSelectedTab } from '../../actions/app';
import { selectedThreadSelectors } from '../../selectors/per-thread';
import { ensureExists } from '../../utils/flow';
import {
autoMockCanvasContext,
flushDrawLog,
} from '../fixtures/mocks/canvas-context';
import { mockRaf } from '../fixtures/mocks/request-animation-frame';
import { storeWithProfile } from '../fixtures/stores';
import {
getMouseEvent,
addRootOverlayElement,
removeRootOverlayElement,
findFillTextPositionFromDrawLog,
fireFullClick,
fireFullContextMenu,
fireFullKeyPress,
} from '../fixtures/utils';
import {
getProfileFromTextSamples,
getProfileWithMarkers,
getUserTiming,
} from '../fixtures/profiles/processed-profile';
import { autoMockElementSize } from '../fixtures/mocks/element-size';
import type { Profile, CssPixels } from 'firefox-profiler/types';
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', () => {
const { container } = setupSamples();
const drawCalls = flushDrawLog();
expect(container.firstChild).toMatchSnapshot();
expect(drawCalls).toMatchSnapshot();
});
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.getSourceViewFile(getState())).toBeNull();
fireFullKeyPress(stackChartCanvas, { key: 'Enter' });
expect(UrlStateSelectors.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');
});
function getDrawnFrames() {
const drawCalls = flushDrawLog();
return drawCalls.filter(([fn]) => fn === 'fillText').map(([, arg]) => arg);
}
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');
});
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();
});
});
});
describe('MarkerChart', function () {
it('can turn on the show user timings', () => {
const { getByLabelText, getState } = setupUserTimings({
isShowUserTimingsClicked: false,
});
const checkbox = getByLabelText('Show user timing');
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 } = setupUserTimings({
isShowUserTimingsClicked: true,
});
expect(getTooltip()).toBe(null);
moveMouse(findFillTextPosition('componentB'));
expect(getTooltip()).toBeTruthy();
expect(getTooltip()).toMatchSnapshot();
});
});
describe('CombinedChart', function () {
it('renders combined stack chart', () => {
const { container } = setupCombinedTimings();
expect(container.firstChild).toMatchSnapshot();
expect(flushDrawLog()).toMatchSnapshot();
});
});
function showUserTimings({ getByLabelText, flushRafCalls }) {
flushDrawLog();
const checkbox = getByLabelText('Show user timing');
fireFullClick(checkbox);
flushRafCalls();
}
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(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(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]
`
) {
const {
profile,
funcNamesPerThread: [funcNames],
} = getProfileFromTextSamples(samples);
return setup(profile, funcNames);
}
/**
* Setup the stack chart component with a profile.
*/
function setup(profile: Profile, funcNames: string[] = []) {
const flushRafCalls = mockRaf();
const store = storeWithProfile(profile);
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`
);
// Mouse event tools
function getPositioningOptions({ x, y }) {
// 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, options) {
fireEvent(stackChartCanvas, getMouseEvent(eventName, options));
}
/**
* The tooltip is in a portal, and created in the root overlay elements.
*/
function getTooltip() {
return document.querySelector('#root-overlay .tooltip');
}
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) {
fireMouseEvent('mousemove', getPositioningOptions(where));
}
// Context menu tools
const getContextMenu = () =>
ensureExists(
container.querySelector('.react-contextmenu'),
`Couldn't find the context menu.`
);
function clickMenuItem(strOrRegexp) {
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): mixed {
return (element: any).checked;
}