tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

testcommon.js (7511B)


      1 /* Any copyright is dedicated to the Public Domain.
      2 * http://creativecommons.org/publicdomain/zero/1.0/ */
      3 
      4 /**
      5 * Use this variable if you specify duration or some other properties
      6 * for script animation.
      7 * E.g., div.animate({ opacity: [0, 1] }, 100 * MS_PER_SEC);
      8 *
      9 * NOTE: Creating animations with short duration may cause intermittent
     10 * failures in asynchronous test. For example, the short duration animation
     11 * might be finished when animation.ready has been fulfilled because of slow
     12 * platforms or busyness of the main thread.
     13 * Setting short duration to cancel its animation does not matter but
     14 * if you don't want to cancel the animation, consider using longer duration.
     15 */
     16 const MS_PER_SEC = 1000;
     17 
     18 /* The recommended minimum precision to use for time values[1].
     19 *
     20 * [1] https://drafts.csswg.org/web-animations/#precision-of-time-values
     21 */
     22 var TIME_PRECISION = 0.0005; // ms
     23 
     24 /*
     25 * Allow implementations to substitute an alternative method for comparing
     26 * times based on their precision requirements.
     27 */
     28 function assert_times_equal(actual, expected, description) {
     29  assert_approx_equals(actual, expected, TIME_PRECISION * 2, description);
     30 }
     31 
     32 /*
     33 * Compare a time value based on its precision requirements with a fixed value.
     34 */
     35 function assert_time_equals_literal(actual, expected, description) {
     36  assert_approx_equals(actual, expected, TIME_PRECISION, description);
     37 }
     38 
     39 /*
     40 * Compare two keyframes
     41 */
     42 function assert_frames_equal(actual, expected, name) {
     43  // TODO: Make this skip the 'composite' member when it is not specified in
     44  // `expected` or when the implementation does not support it.
     45  assert_array_equals(
     46    Object.keys(actual).sort(),
     47    Object.keys(expected).sort(),
     48    `properties on ${name} should match`
     49  );
     50 
     51  // Iterates sorted keys to ensure stable failures.
     52  for (const prop of Object.keys(actual).sort()) {
     53    if (
     54      // 'offset' can be null
     55      (prop === 'offset' && typeof actual[prop] === 'number') ||
     56      prop === 'computedOffset'
     57    ) {
     58      assert_approx_equals(
     59        actual[prop],
     60        expected[prop],
     61        0.00001,
     62        "value for '" + prop + "' on " + name
     63      );
     64    } else {
     65      assert_equals(
     66        actual[prop],
     67        expected[prop],
     68        `value for '${prop}' on ${name} should match`
     69      );
     70    }
     71  }
     72 }
     73 
     74 /*
     75 * Compare two lists of keyframes
     76 */
     77 function assert_frame_lists_equal(actual, expected) {
     78  assert_equals(
     79    actual.length,
     80    expected.length,
     81    'Number of keyframes should match'
     82  );
     83 
     84  for (let i = 0; i < actual.length; i++) {
     85    assert_frames_equal(actual[i], expected[i], `Keyframe #${i}`);
     86  }
     87 }
     88 
     89 /**
     90 * Appends an element to the document body.
     91 *
     92 * @param t  The testharness.js Test object. If provided, this will be used
     93 *           to register a cleanup callback to remove the div when the test
     94 *           finishes.
     95 *
     96 * @param name  A string specifying the element name.
     97 *
     98 * @param attrs  A dictionary object with attribute names and values to set on
     99 *               the div.
    100 */
    101 function addElement(t, name, attrs) {
    102  var element = document.createElement(name);
    103  if (attrs) {
    104    for (var attrName in attrs) {
    105      element.setAttribute(attrName, attrs[attrName]);
    106    }
    107  }
    108  document.body.appendChild(element);
    109  if (t && typeof t.add_cleanup === 'function') {
    110      t.add_cleanup(() => element.remove());
    111  }
    112  return element;
    113 }
    114 
    115 /**
    116 * Appends a div to the document body.
    117 *
    118 * @param t  The testharness.js Test object. If provided, this will be used
    119 *           to register a cleanup callback to remove the div when the test
    120 *           finishes.
    121 *
    122 * @param attrs  A dictionary object with attribute names and values to set on
    123 *               the div.
    124 */
    125 function addDiv(t, attrs) {
    126  return addElement(t, "div", attrs);
    127 }
    128 
    129 /**
    130 * Appends a style div to the document head.
    131 *
    132 * @param t  The testharness.js Test object. If provided, this will be used
    133 *           to register a cleanup callback to remove the style element
    134 *           when the test finishes.
    135 *
    136 * @param rules  A dictionary object with selector names and rules to set on
    137 *               the style sheet.
    138 */
    139 function addStyle(t, rules) {
    140  var extraStyle = document.createElement('style');
    141  document.head.appendChild(extraStyle);
    142  if (rules) {
    143    var sheet = extraStyle.sheet;
    144    for (var selector in rules) {
    145      sheet.insertRule(selector + '{' + rules[selector] + '}',
    146                       sheet.cssRules.length);
    147    }
    148  }
    149 
    150  if (t && typeof t.add_cleanup === 'function') {
    151    t.add_cleanup(function() {
    152      extraStyle.remove();
    153    });
    154  }
    155 }
    156 
    157 /**
    158 * Promise wrapper for requestAnimationFrame.
    159 */
    160 function waitForFrame() {
    161  return new Promise(function(resolve, reject) {
    162    window.requestAnimationFrame(resolve);
    163  });
    164 }
    165 
    166 /**
    167 * Waits for a requestAnimationFrame callback in the next refresh driver tick.
    168 */
    169 function waitForNextFrame() {
    170  const timeAtStart = document.timeline.currentTime;
    171  return new Promise(resolve => {
    172    window.requestAnimationFrame(() => {
    173      if (timeAtStart === document.timeline.currentTime) {
    174        window.requestAnimationFrame(resolve);
    175      } else {
    176        resolve();
    177      }
    178    });
    179  });
    180 }
    181 
    182 /**
    183 * Returns a Promise that is resolved after the given number of consecutive
    184 * animation frames have occured (using requestAnimationFrame callbacks).
    185 *
    186 * @param frameCount  The number of animation frames.
    187 * @param onFrame  An optional function to be processed in each animation frame.
    188 */
    189 function waitForAnimationFrames(frameCount, onFrame) {
    190  const timeAtStart = document.timeline.currentTime;
    191  return new Promise(function(resolve, reject) {
    192    function handleFrame() {
    193      if (onFrame && typeof onFrame === 'function') {
    194        onFrame();
    195      }
    196      if (timeAtStart != document.timeline.currentTime &&
    197          --frameCount <= 0) {
    198        resolve();
    199      } else {
    200        window.requestAnimationFrame(handleFrame); // wait another frame
    201      }
    202    }
    203    window.requestAnimationFrame(handleFrame);
    204  });
    205 }
    206 
    207 /**
    208 * Timeout function used for tests with EventWatchers when all animation events
    209 * should be received on the next animation frame. If two frames pass before
    210 * receiving the expected events, then we can immediate fail the test.
    211 */
    212 function fastEventsTimeout() {
    213  return waitForAnimationFrames(2);
    214 };
    215 
    216 /**
    217 * Timeout function used for tests with EventWatchers. The client agent has no
    218 * strict requirement for how long it takes to resolve the ready promise. Once
    219 * the promise is resolved a secondary timeout promise is armed that may have
    220 * a tight deadline measured in animation frames.
    221 */
    222 function armTimeoutWhenReady(animation, timeoutPromise) {
    223  return () => {
    224    if (animation.pending)
    225      return animation.ready.then(() => { return timeoutPromise(); });
    226    else
    227      return timeoutPromise();
    228  };
    229 }
    230 
    231 /**
    232 * Wrapper that takes a sequence of N animations and returns:
    233 *
    234 *   Promise.all([animations[0].ready, animations[1].ready, ... animations[N-1].ready]);
    235 */
    236 function waitForAllAnimations(animations) {
    237  return Promise.all(animations.map(animation => animation.ready));
    238 }
    239 
    240 /**
    241 * Flush the computed style for the given element. This is useful, for example,
    242 * when we are testing a transition and need the initial value of a property
    243 * to be computed so that when we synchronouslyet set it to a different value
    244 * we actually get a transition instead of that being the initial value.
    245 */
    246 function flushComputedStyle(elem) {
    247  var cs = getComputedStyle(elem);
    248  cs.marginLeft;
    249 }