summaryrefslogtreecommitdiffstats
path: root/testing/talos/talos/tests/devtools/addon/content/tests/debugger/debugger-helpers.js
blob: 53ad52e65e8eb610f7fb05bcc8a2ac86385b57e8 (plain)
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
/* 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/. */

"use strict";

const { openToolboxAndLog, reloadPageAndLog } = require("../head");
const {
  createLocation,
} = require("devtools/client/debugger/src/utils/location");

/*
 * These methods are used for working with debugger state changes in order
 * to make it easier to manipulate the ui and test different behavior. These
 * methods roughly reflect those found in debugger/test/mochi/head.js with
 * a few exceptions. The `dbg` object is not exactly the same, and the methods
 * have been simplified. We may want to consider unifying them in the future
 */

const DEBUGGER_POLLING_INTERVAL = 25;

function waitForState(dbg, predicate, msg) {
  return new Promise(resolve => {
    if (msg) {
      dump(`Waiting for state change: ${msg}\n`);
    }
    if (predicate(dbg.store.getState())) {
      if (msg) {
        dump(`Finished waiting for state change: ${msg}\n`);
      }
      return resolve();
    }

    const unsubscribe = dbg.store.subscribe(() => {
      if (predicate(dbg.store.getState())) {
        if (msg) {
          dump(`Finished waiting for state change: ${msg}\n`);
        }
        unsubscribe();
        resolve();
      }
    });
    return false;
  });
}
exports.waitForState = waitForState;

function waitForDispatch(dbg, type, count = 1) {
  return new Promise(resolve => {
    dbg.store.dispatch({
      type: "@@service/waitUntil",
      predicate: action => {
        if (
          action.type === type &&
          (!action.status ||
            action.status === "done" ||
            action.status === "error")
        ) {
          --count;
          if (count === 0) {
            return true;
          }
        }
        return false;
      },
      run: (dispatch, getState, action) => {
        resolve(action);
      },
    });
  });
}

async function waitUntil(predicate, msg) {
  if (msg) {
    dump(`Waiting until: ${msg}\n`);
  }
  const earlyPredicateResult = predicate();
  if (earlyPredicateResult) {
    if (msg) {
      dump(`Finished Waiting until: ${msg} (was immediately true)\n`);
    }
    return earlyPredicateResult;
  }
  return new Promise(resolve => {
    const timer = setInterval(() => {
      const predicateResult = predicate();
      if (predicateResult) {
        clearInterval(timer);
        if (msg) {
          dump(`Finished Waiting until: ${msg}\n`);
        }
        resolve(predicateResult);
      }
    }, DEBUGGER_POLLING_INTERVAL);
  });
}
exports.waitUntil = waitUntil;

function findSource(dbg, url) {
  const sources = dbg.selectors.getSourceList(dbg.getState());
  return sources.find(s => (s.url || "").includes(url));
}
exports.findSource = findSource;

function getCM(dbg) {
  const el = dbg.win.document.querySelector(".CodeMirror");
  return el.CodeMirror;
}
exports.getCM = getCM;

function waitForText(dbg, text) {
  return waitUntil(() => {
    // the welcome box is removed once text is displayed
    const welcomebox = dbg.win.document.querySelector(".welcomebox");
    if (welcomebox) {
      return false;
    }
    const cm = getCM(dbg);
    const editorText = cm.doc.getValue();
    return editorText.includes(text);
  }, "text is visible");
}
exports.waitForText = waitForText;

function waitForSymbols(dbg) {
  return waitUntil(() => {
    const state = dbg.store.getState();
    const location = dbg.selectors.getSelectedLocation(state);
    return dbg.selectors.getSymbols(state, location);
  }, "has file metadata");
}

function waitForSources(dbg, expectedSources) {
  const { selectors } = dbg;
  function countSources(state) {
    return selectors.getSourceCount(state) >= expectedSources;
  }
  return waitForState(dbg, countSources, "count sources");
}

function waitForSource(dbg, sourceURL) {
  const { selectors } = dbg;
  function hasSource(state) {
    return selectors.getSourceByURL(state, sourceURL);
  }
  return waitForState(dbg, hasSource, `has source ${sourceURL}`);
}
exports.waitForSource = waitForSource;

function waitForThreadCount(dbg, count) {
  const { selectors } = dbg;
  function threadCount(state) {
    // getThreads doesn't count the main thread
    // and don't use getAllThreads as it does useless expensive computations.
    return selectors.getThreads(state).length + 1 == count;
  }
  return waitForState(dbg, threadCount, `has source ${count} threads`);
}

async function waitForPaused(
  dbg,
  pauseOptions = { shouldWaitForLoadedScopes: true }
) {
  const promises = [];

  // If original variable mapping is disabled the scopes for
  // original sources are not loaded by default so lets not
  // wait for any scopes.
  if (pauseOptions.shouldWaitForLoadedScopes) {
    promises.push(waitForLoadedScopes(dbg));
  }
  const {
    selectors: { getSelectedScope, getIsPaused, getCurrentThread },
  } = dbg;
  const onStateChange = waitForState(dbg, state => {
    const thread = getCurrentThread(state);
    return getSelectedScope(state, thread) && getIsPaused(state, thread);
  });
  promises.push(onStateChange);
  return Promise.all(promises);
}
exports.waitForPaused = waitForPaused;

async function waitForResumed(dbg) {
  const {
    selectors: { getIsPaused, getCurrentThread },
  } = dbg;
  return waitForState(
    dbg,
    state => !getIsPaused(state, getCurrentThread(state))
  );
}

async function waitForElement(dbg, name) {
  await waitUntil(() => dbg.win.document.querySelector(name));
  return dbg.win.document.querySelector(name);
}

async function waitForLoadedScopes(dbg) {
  // Since scopes auto-expand, we can assume they are loaded when there is a tree node
  // with the aria-level attribute equal to "2".
  const element = '.scopes-list .tree-node[aria-level="2"]';
  return waitForElement(dbg, element);
}

function clickElement(dbg, selector) {
  const clickEvent = new dbg.win.MouseEvent("click", {
    bubbles: true,
    cancelable: true,
    view: dbg.win,
  });
  dbg.win.document.querySelector(selector).dispatchEvent(clickEvent);
}

async function toggleOriginalScopes(dbg) {
  const scopesLoaded = waitForLoadedScopes(dbg);
  const onDispatch = waitForDispatch(dbg, "TOGGLE_MAP_SCOPES");
  clickElement(dbg, ".map-scopes-header input");
  return Promise.all([onDispatch, scopesLoaded]);
}

function createContext(panel) {
  const { store, selectors, actions } = panel.getVarsForTests();

  return {
    actions,
    selectors,
    getState: store.getState,
    win: panel.panelWin,
    store,
  };
}
exports.createContext = createContext;

async function selectSource(dbg, url) {
  dump(`Selecting source: ${url}\n`);
  const line = 1;
  const source = findSource(dbg, url);
  // keepContext set to false allows to force selecting original/generated source
  // regardless if we were currently selecting the opposite type of source.
  await dbg.actions.selectLocation(createLocation({ source, line }), {
    keepContext: false,
  });
  return waitForState(
    dbg,
    state => {
      const location = dbg.selectors.getSelectedLocation(state);
      if (!location) {
        return false;
      }
      if (location.source != source || location.line != line) {
        return false;
      }
      const sourceTextContent =
        dbg.selectors.getSelectedSourceTextContent(state);
      if (!sourceTextContent) {
        return false;
      }

      // wait for symbols -- a flat map of all named variables in a file -- to be calculated.
      // this is a slow process and becomes slower the larger the file is
      return dbg.selectors.getSymbols(state, location);
    },
    "selected source"
  );
}
exports.selectSource = selectSource;

function evalInFrame(tab, testFunction) {
  dump(`Run function in content process: ${testFunction}\n`);
  // Load a frame script using a data URI so we can run a script
  // inside of the content process and trigger debugger functionality
  // as needed
  const messageManager = tab.linkedBrowser.messageManager;
  return messageManager.loadFrameScript(
    "data:,(" +
      encodeURIComponent(`
        function () {
          const iframe = content.document.querySelector("iframe");
          const win = iframe.contentWindow;
          win.eval(\`${testFunction}\`);
        }`) +
      ")()",
    true
  );
}
exports.evalInFrame = evalInFrame;

async function openDebuggerAndLog(label, expected) {
  const onLoad = async (toolbox, panel) => {
    const dbg = await createContext(panel);
    await waitForThreadCount(dbg, expected.threadsCount);
    await waitForSource(dbg, expected.sourceURL);
    await selectSource(dbg, expected.file);
    await waitForText(dbg, expected.text);
    await waitForSymbols(dbg);
  };

  const toolbox = await openToolboxAndLog(
    label + ".jsdebugger",
    "jsdebugger",
    onLoad
  );
  return toolbox;
}
exports.openDebuggerAndLog = openDebuggerAndLog;

async function reloadDebuggerAndLog(label, toolbox, expected) {
  const onReload = async () => {
    const panel = await toolbox.getPanelWhenReady("jsdebugger");
    const dbg = await createContext(panel);

    // First wait for all previous page threads to be removed
    await waitForDispatch(dbg, "REMOVE_THREAD", expected.threadsCount);
    // Only after that wait for all new threads to be registered before doing more assertions
    // Otherwise we may resolve too soon on previous page sources.
    await waitForThreadCount(dbg, expected.threadsCount);

    await waitForSources(dbg, expected.sources);
    await waitForSource(dbg, expected.sourceURL);
    await waitForText(dbg, expected.text);
    await waitForSymbols(dbg);
  };
  await reloadPageAndLog(`${label}.jsdebugger`, toolbox, onReload);
}
exports.reloadDebuggerAndLog = reloadDebuggerAndLog;

async function addBreakpoint(dbg, line, url) {
  dump(`add breakpoint\n`);
  const source = findSource(dbg, url);
  const location = createLocation({
    source,
    line,
  });

  await selectSource(dbg, url);

  await dbg.actions.addBreakpoint(location);
}
exports.addBreakpoint = addBreakpoint;

async function removeBreakpoints(dbg) {
  dump(`remove all breakpoints\n`);
  const breakpoints = dbg.selectors.getBreakpointsList(dbg.getState());

  const onBreakpointsCleared = waitForState(
    dbg,
    state => dbg.selectors.getBreakpointCount(state) === 0
  );
  await dbg.actions.removeBreakpoints(breakpoints);
  return onBreakpointsCleared;
}
exports.removeBreakpoints = removeBreakpoints;

async function pauseDebugger(dbg, tab, testFunction, { line, file }) {
  const { getSelectedLocation, isMapScopesEnabled } = dbg.selectors;

  const state = dbg.store.getState();
  const selectedSource = getSelectedLocation(state).source;

  await addBreakpoint(dbg, line, file);
  const shouldEnableOriginalScopes =
    selectedSource.isOriginal &&
    !selectedSource.isPrettyPrinted &&
    !isMapScopesEnabled(state);

  const onPaused = waitForPaused(dbg, {
    shouldWaitForLoadedScopes: !shouldEnableOriginalScopes,
  });
  await evalInFrame(tab, testFunction);

  if (shouldEnableOriginalScopes) {
    await onPaused;
    await toggleOriginalScopes(dbg);
  }
  return onPaused;
}
exports.pauseDebugger = pauseDebugger;

async function resume(dbg) {
  const onResumed = waitForResumed(dbg);
  dbg.actions.resume();
  return onResumed;
}
exports.resume = resume;

async function step(dbg, stepType) {
  const resumed = waitForResumed(dbg);
  dbg.actions[stepType]();
  await resumed;
  return waitForPaused(dbg);
}
exports.step = step;

async function hoverOnToken(dbg, textToWaitFor, textToHover) {
  await waitForText(dbg, textToWaitFor);
  const tokenElement = [
    ...dbg.win.document.querySelectorAll(".CodeMirror span"),
  ].find(el => el.textContent === textToHover);

  const mouseOverEvent = new dbg.win.MouseEvent("mouseover", {
    bubbles: true,
    cancelable: true,
    view: dbg.win,
  });
  tokenElement.dispatchEvent(mouseOverEvent);
  const mouseMoveEvent = new dbg.win.MouseEvent("mousemove", {
    bubbles: true,
    cancelable: true,
    view: dbg.win,
  });
  tokenElement.dispatchEvent(mouseMoveEvent);

  // Unfortunately, dispatching mouseover/mousemove manually via MouseEvent
  // isn't enough to toggle the :hover, so manually toggle it.
  // (For some reason, the EventUtils helpers used by mochitests help)
  InspectorUtils.addPseudoClassLock(tokenElement, ":hover", true);

  dump("Waiting for the preview popup to show\n");
  await waitUntil(() =>
    tokenElement.ownerDocument.querySelector(".preview-popup")
  );

  const mouseOutEvent = new dbg.win.MouseEvent("mouseout", {
    bubbles: true,
    cancelable: true,
    view: dbg.win,
  });
  tokenElement.dispatchEvent(mouseOutEvent);

  const mouseMoveOutEvent = new dbg.win.MouseEvent("mousemove", {
    bubbles: true,
    cancelable: true,
    view: dbg.win,
  });
  // See shared-head file, for why picking this element
  const element = tokenElement.ownerDocument.querySelector(
    ".debugger-settings-menu-button"
  );
  element.dispatchEvent(mouseMoveOutEvent);

  InspectorUtils.removePseudoClassLock(tokenElement, ":hover");

  dump("Waiting for the preview popup to hide\n");
  await waitUntil(
    () => !tokenElement.ownerDocument.querySelector(".preview-popup")
  );
}
exports.hoverOnToken = hoverOnToken;