<!DOCTYPE html>
<html>
<head>
<title>Cache Storage: testing persistency of different origins</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
</head>
<body>
    <script>

    async function checkCachesAfterClearingMemoryRepresentation(name) {
        await internals.clearCacheStorageMemoryRepresentation();
        var keys = await self.caches.keys();
        test(() => {
            assert_true(keys.indexOf("cache1") !== -1, "Should have cache1");
            assert_true(keys.indexOf("cache2") === -1, "Should not have cache2");
        }, "Verifying that caches are clustered per client origin.");
    }

    async function checkCachesAfterClearingOrigins() {
        testRunner.clearDOMCache('https://127.0.0.1:8443');
        var representation = JSON.parse(await internals.cacheStorageEngineRepresentation()).origins;
        test(() => {
            assert_equals(representation.length, 0);
        }, "Verifying that clearing caches for an origin will clear both top origin and client origin caches.");
    }

    async function checkCacheRepresentation() {
        var representation = JSON.parse(await internals.cacheStorageEngineRepresentation()).origins;
        test(() => {
            assert_equals(representation[0].origin.topOrigin, "https://127.0.0.1:8443", "top origin of cache 1");
            assert_equals(representation[1].origin.topOrigin, "https://127.0.0.1:8443", "top origin of cache 2");
            assert_equals(representation[0].origin.clientOrigin, "https://127.0.0.1:8443", "client origin of cache 1");
            assert_equals(representation[1].origin.clientOrigin, "https://localhost:8443", "client origin of cache 2");
            assert_array_equals(representation[0].caches.persistent, ["cache1"]);
            assert_array_equals(representation[1].caches.persistent, ["cache2"]);
        }, "Verifying that two caches are created on two different client origins");
    }

    promise_test(test => {
        if (!window.internals || !window.testRunner)
            return Promise.reject("Test requires internals and test runner");

        return new Promise((resolve, reject) => {
            var counter = 0;
            window.addEventListener("message", test.step_func(async (event) => {
                if (++counter <= 1)
                    return;

                await checkCacheRepresentation();
                await checkCachesAfterClearingMemoryRepresentation();
                await checkCachesAfterClearingOrigins();
                resolve();
            }));
        })
    }, "Create a cache storage and look at the representation");
    </script>
    <div>
        <iframe src="resources/cache-persistency-iframe.html#name=cache1"></iframe>
        <iframe src="https://localhost:8443/cache-storage/resources/cache-persistency-iframe.html#name=cache2"></iframe>
    </div>
</body>
</html>
