<html>
<head>
<title>Service Worker triggering server trust evaluation</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/service-workers/service-worker/resources/test-helpers.sub.js"></script>
</head>
<body>
<script>
var registration;
var iframe;
promise_test(async (test) => {
    if (window.testRunner) {
        testRunner.terminateNetworkProcess();
        await fetch("").then(() => { }, () => { });
    }

    registration = await navigator.serviceWorker.getRegistration("resources/");
    if (registration)
        await registration.unregister();
    registration = await navigator.serviceWorker.register("server-trust-worker.js", { scope : "resources/" });
    activeWorker = registration.active;
    if (activeWorker)
        return;
    activeWorker = registration.installing;
    await new Promise(resolve => {
        activeWorker.addEventListener('statechange', () => {
            if (activeWorker.state === "activated")
                resolve();
        });
    });
}, "Setup worker");

promise_test(async (test) => {
    let count;
    if (window.testRunner) {
        testRunner.setAllowsAnySSLCertificate(false);
        count = testRunner.serverTrustEvaluationCallbackCallsCount;
    }

    iframe = await with_iframe("resources/iframe1.html");
    assert_true(iframe.contentWindow.document.body.innerHTML.trim().indexOf("Load failed: ") !== -1);
    iframe.remove();

    if (window.testRunner)
        assert_equals(testRunner.serverTrustEvaluationCallbackCallsCount, count + 1);

}, "Service worker load should fail");

promise_test(async (test) => {
    let count;
    if (window.testRunner) {
        window.testRunner.setAllowsAnySSLCertificate(true);
        count = testRunner.serverTrustEvaluationCallbackCallsCount;
    }

    iframe = await with_iframe("resources/iframe2.html");
    assert_true(iframe.contentWindow.document.body.innerHTML.trim().indexOf("PASS") !== -1);
    iframe.remove();

    if (window.testRunner)
        assert_equals(testRunner.serverTrustEvaluationCallbackCallsCount, count + 1);
}, "Service worker load should succeed");
</script>
</body>
</html>
