<script src="/js-test-resources/js-test-pre.js"></script>
<script src="resources/cache-test.js"></script>
<body>
<script>
window.jsTestIsAsync = true;

description("Tests that resources are removed from the cache if they become uncacheable");

var uniqueTestId = Math.floor((Math.random() * 1000000000000));

function loadResource(cacheable, onload)
{
    internals.clearMemoryCache();

    xhr = new XMLHttpRequest();
    xhr.onload = onload;
    xhr.open("GET", "resources/generate-response-optionally-cacheable.cgi?uniqueId=" + uniqueTestId, true);

    xhr.setRequestHeader("X-Cacheable", cacheable ? "true" : "false");
    xhr.send(null);
}

loadResource(true, function() {
    // Wait a bit so things settle down in the disk cache.
    setTimeout(function () {
        debug("Resource should be in the cache now.");
        debug("Load resource again using default cache policy.")
        loadResource(true, function() {
            shouldBeEqualToString("internals.xhrResponseSource(xhr)", "Disk cache");

            debug("");
            debug("Now load again the same resource, ignoring the cached data.");
            internals.setOverrideCachePolicy("ReloadIgnoringCacheData");

            debug("This time the resource will not be cacheable");
            loadResource(false, function() {
                shouldBeEqualToString("internals.xhrResponseSource(xhr)", "Network");

                setTimeout(function() {
                debug("");
                debug("Stale resource should have been removed from the cache.");

                debug("");
                debug("Now try to load the resource from the cache.");
                internals.setOverrideCachePolicy("UseProtocolCachePolicy");
                loadResource(false, function() {
                     shouldBeEqualToString("internals.xhrResponseSource(xhr)", "Network");
                     finishJSTest();
                });
                }, 100);
            });
        });
    }, 100);
});

</script>
<script src="/js-test-resources/js-test-post.js"></script>
