<!doctype html>
<html>
<title> Images on a page Cross-Origin-Embedder-Policy: require-corp should load the same from the cache or network</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/get-host-info.sub.js"></script>
<script src="/common/utils.js"></script>
<script>

function remote(path) {
  const REMOTE_ORIGIN = get_host_info().HTTPS_REMOTE_ORIGIN;
  return new URL(path, REMOTE_ORIGIN);
}

//
// This test loads a same-origin iframe resources/load-corp-images.html with
// Cross-Origin-Embedder-Policy: require-corp
// The iframe loads two cross origin images, one with a
// Cross-Origin-Resource-Policy: cross-origin header, and one without.
// We expect the image with the header to load successfully and the one without
// to fail to load.
// After the first load we then reload the iframe, with the same expectations
// for the image loads when they are loaded from the cache.
//

const RUNS = ["NETWORK", "CACHED"];
const RESOURCE_DESC = ["No CORP image", "CORP image"];

let EXPECTED_LOADS = {
  [`${RUNS[0]} - ${RESOURCE_DESC[0]}`]: false,
  [`${RUNS[0]} - ${RESOURCE_DESC[1]}`]: true,
  [`${RUNS[1]} - ${RESOURCE_DESC[0]}`]: false,
  [`${RUNS[1]} - ${RESOURCE_DESC[1]}`]: true,
}

let TESTS = {};
for (let t in EXPECTED_LOADS) {
  TESTS[t] = async_test(t);
}

window.addEventListener("load", async () => {
  const t = async_test("main_test");
  const iframe = document.createElement("iframe");
  // The token attribute is used to ensure the resource has never been seen by
  // the HTTP cache. This can be useful if the cache isn't properly flushed in
  // between two tests.
  iframe.src = `resources/load-corp-images.html?revalidate=false&token=${token()}`;
  let runCount = 0;
  window.addEventListener("message", (event) => {
    // After the first done event we reload the iframe.
    if (event.data.done) {
      ++runCount;
      if (runCount < RUNS.length) {
        iframe.contentWindow.location.reload();
      } else {
        // After the second done event the test is finished.
        t.done();
      }
      return;
    }

    // Check that each image either loads or doesn't based on the expectations
    let testName = `${RUNS[runCount]} - ${event.data.corp ? RESOURCE_DESC[1] : RESOURCE_DESC[0]}`;
    let test = TESTS[testName];
    test.step(() => {
      assert_equals(event.data.loaded, EXPECTED_LOADS[testName], `${testName} should ${EXPECTED_LOADS[testName] ? "" : "not"} succeed`);
    });
    test.done();
  }, false);
  document.body.appendChild(iframe);
});

</script>
</html>
