Bug 1462990 - Use async/await in mediasource/test/mediasource.js draft
authorJan-Ivar Bruaroey <jib@mozilla.com>
Fri, 18 May 2018 10:26:11 -0400
changeset 801140 48a9b8b74f1b45b089c5ce426aa8a001137b8b6d
parent 800874 f01bb6245db1ea2a87e5360104a4110571265137
child 801141 45949412c6084666e29f880c2c2576c9c7c61d11
push id111591
push userjbruaroey@mozilla.com
push dateTue, 29 May 2018 20:32:24 +0000
bugs1462990
milestone62.0a1
Bug 1462990 - Use async/await in mediasource/test/mediasource.js MozReview-Commit-ID: BnQ30DnY4mB
dom/media/mediasource/test/mediasource.js
--- a/dom/media/mediasource/test/mediasource.js
+++ b/dom/media/mediasource/test/mediasource.js
@@ -6,118 +6,103 @@ let gMSETestPrefs = [
   [ "media.video-max-decode-error", 0 ],
 ];
 
 // Called before runWithMSE() to set the prefs before running MSE tests.
 function addMSEPrefs(...prefs) {
   gMSETestPrefs = gMSETestPrefs.concat(prefs);
 }
 
-function runWithMSE(testFunction) {
-  function bootstrapTest() {
-    const ms = new MediaSource();
+async function runWithMSE(testFunction) {
+  await once(window, "load");
+  await SpecialPowers.pushPrefEnv({"set": gMSETestPrefs});
 
-    const el = document.createElement("video");
-    el.src = URL.createObjectURL(ms);
-    el.preload = "auto";
+  const ms = new MediaSource();
+
+  const el = document.createElement("video");
+  el.src = URL.createObjectURL(ms);
+  el.preload = "auto";
 
-    document.body.appendChild(el);
-    SimpleTest.registerCleanupFunction(function() {
-      el.remove();
-      el.removeAttribute("src");
-      el.load();
-    });
-
-    testFunction(ms, el);
+  document.body.appendChild(el);
+  SimpleTest.registerCleanupFunction(() => {
+    el.remove();
+    el.removeAttribute("src");
+    el.load();
+  });
+  try {
+    await testFunction(ms, el);
+  } catch (e) {
+    ok(false, `${testFunction.name} failed with error ${e.name}`);
+    throw e;
   }
-
-  addLoadEvent(function() {
-    SpecialPowers.pushPrefEnv({"set": gMSETestPrefs}, bootstrapTest);
-  });
 }
 
-function fetchWithXHR(uri, onLoadFunction) {
-  const p = new Promise(function(resolve, reject) {
+async function fetchWithXHR(uri, onLoadFunction) {
+  let result = await new Promise(resolve => {
     const xhr = new XMLHttpRequest();
     xhr.open("GET", uri, true);
     xhr.responseType = "arraybuffer";
     xhr.addEventListener("load", function() {
       is(xhr.status, 200, "fetchWithXHR load uri='" + uri + "' status=" + xhr.status);
       resolve(xhr.response);
     });
     xhr.send();
   });
 
   if (onLoadFunction) {
-    p.then(onLoadFunction);
+    result = await onLoadFunction(result);
   }
-
-  return p;
+  return result;
 }
 
 function range(start, end) {
   const rv = [];
   for (let i = start; i < end; ++i) {
     rv.push(i);
   }
   return rv;
 }
 
-function once(target, name, cb) {
-  const p = new Promise(function(resolve, reject) {
-    target.addEventListener(name, function() {
-      resolve();
-    }, {once: true});
-  });
+async function once(target, name, cb) {
+  let result = await new Promise(r => target.addEventListener(name, r, {once: true}));
   if (cb) {
-    p.then(cb);
+    result = await cb();
   }
-  return p;
+  return result;
 }
 
 function timeRangeToString(r) {
   let str = "TimeRanges: ";
   for (let i = 0; i < r.length; i++) {
     str += "[" + r.start(i) + ", " + r.end(i) + ")";
   }
   return str;
 }
 
-function loadSegment(sb, typedArrayOrArrayBuffer) {
+async function loadSegment(sb, typedArrayOrArrayBuffer) {
   const typedArray = (typedArrayOrArrayBuffer instanceof ArrayBuffer) ? new Uint8Array(typedArrayOrArrayBuffer)
                                                                       : typedArrayOrArrayBuffer;
   info(`Loading buffer: [${typedArray.byteOffset}, ${typedArray.byteOffset + typedArray.byteLength})`);
   const beforeBuffered = timeRangeToString(sb.buffered);
-  return new Promise(function(resolve, reject) {
-    once(sb, "update").then(function() {
-      const afterBuffered = timeRangeToString(sb.buffered);
-      info(`SourceBuffer buffered ranges grew from ${beforeBuffered} to ${afterBuffered}`);
-      resolve();
-    });
-    sb.appendBuffer(typedArray);
-  });
+  const p = once(sb, 'update');
+  sb.appendBuffer(typedArray);
+  await p;
+  const afterBuffered = timeRangeToString(sb.buffered);
+  info(`SourceBuffer buffered ranges grew from ${beforeBuffered} to ${afterBuffered}`);
 }
 
-function fetchAndLoad(sb, prefix, chunks, suffix) {
+async function fetchAndLoad(sb, prefix, chunks, suffix) {
 
   // Fetch the buffers in parallel.
-  const buffers = {};
-  const fetches = [];
-  for (const chunk of chunks) {
-    fetches.push(fetchWithXHR(prefix + chunk + suffix).then(((c, x) => buffers[c] = x).bind(null, chunk)));
-  }
+  const buffers = await Promise.all(chunks.map(c => fetchWithXHR(prefix + c + suffix)));
 
   // Load them in series, as required per spec.
-  return Promise.all(fetches).then(function() {
-    let rv = Promise.resolve();
-    for (const chunk of chunks) {
-      rv = rv.then(loadSegment.bind(null, sb, buffers[chunk]));
-    }
-    return rv;
-  });
+  for (const buffer of buffers) {
+    await loadSegment(sb, buffer);
+  }
 }
 
 function loadSegmentAsync(sb, typedArrayOrArrayBuffer) {
   const typedArray = (typedArrayOrArrayBuffer instanceof ArrayBuffer) ? new Uint8Array(typedArrayOrArrayBuffer)
                                                                       : typedArrayOrArrayBuffer;
   info(`Loading buffer2: [${typedArray.byteOffset}, ${typedArray.byteOffset + typedArray.byteLength})`);
   const beforeBuffered = timeRangeToString(sb.buffered);
   return sb.appendBufferAsync(typedArray).then(() => {
@@ -150,20 +135,20 @@ SimpleTest.registerTimeoutFunction(funct
   for (const v of document.getElementsByTagName("video")) {
     v.mozDumpDebugInfo();
   }
   for (const a of document.getElementsByTagName("audio")) {
     a.mozDumpDebugInfo();
   }
 });
 
-function waitUntilTime(target, targetTime) {
-  return new Promise(function(resolve, reject) {
+async function waitUntilTime(target, targetTime) {
+  await new Promise(resolve => {
     target.addEventListener("waiting", function onwaiting() {
       info("Got a waiting event at " + target.currentTime);
       if (target.currentTime >= targetTime) {
-        ok(true, "Reached target time of: " + targetTime);
         target.removeEventListener("waiting", onwaiting);
         resolve();
       }
     });
   });
+  ok(true, "Reached target time of: " + targetTime);
 }