Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tests to verify preload caching behavior #31539

Merged
merged 7 commits into from
Dec 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions preload/preload-invalid-resources.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<!doctype html>
<script src="/resources/testharness.js"></script>
noamr marked this conversation as resolved.
Show resolved Hide resolved
<script src="/resources/testharnessreport.js"></script>
<script src="/common/utils.js"></script>
<script src="/preload/resources/preload_helper.js"></script>
<body>
<script>

const invalidImages = {
'invalid data': '/preload/resources/echo-with-cors.py?type=image/svg+xml&content=junk',
missing: '/nothing.png'
}

Object.entries(invalidImages).forEach(([name, url]) => {
promise_test(async t => {
const invalidImageURL = getAbsoluteURL(url)
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'image';
link.href = url;
document.head.appendChild(link);
t.add_cleanup(() => link.remove());
await new Promise(resolve => {
const img = document.createElement('img');
img.src = url;
img.onerror = resolve;
document.body.appendChild(img);
t.add_cleanup(() => img.remove());
});
verifyNumberOfResourceTimingEntries(url, 1);
}, `Preloading an invalid image (${name}) should preload and not re-fetch`)
})

</script>
</body>
164 changes: 164 additions & 0 deletions preload/preload-resource-match.https.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
<!doctype html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/utils.js"></script>
<script src="/preload/resources/preload_helper.js"></script>
<script src="/common/get-host-info.sub.js"></script>
<script>

const {HTTPS_REMOTE_ORIGIN} = get_host_info();

function createEchoURL(text, type) {
return `/preload/resources/echo-with-cors.py?type=${
encodeURIComponent(type)}&content=${
encodeURIComponent(text)}`
}
const urls = {
image: createEchoURL('<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2" />', 'image/svg+xml'),
font: '/preload/resources/font.ttf?x',
text: createEchoURL('hello', 'text/plain'),
script: createEchoURL('function dummy() { }', 'application/javascript'),
style: createEchoURL('.cls { }', 'text/css'),
}

const resourceTypes = {
image: {url: urls.image, as: 'image'},
font: {url: urls.font, as: 'font', config: 'anonymous'},
backgroundImage: {url: urls.image, as: 'image', config: 'no-cors'},
fetch: {url: urls.text, as: 'fetch'},
script: {url: urls.script, as: 'script'},
module: {url: urls.script, as: 'script'},
style: {url: urls.style, as: 'style'}
}

const configs = {
// The requested URL is from the same origin
'same-origin': {crossOrigin: false, attributes: {}},

// The requested URL is from a remote origin, without CORS
'no-cors': {crossOrigin: true, attributes: {}},

// The requested URL is from a remote origin, with CORS (anonymous)
'anonymous': {crossOrigin: true, attributes: {crossOrigin: 'anonymous'}},

// The requested URL is from a remote origin, with CORS (including credentials)
'use-credentials': {crossOrigin: true, attributes: {crossOrigin: 'use-credentials'}},
}

function preload(attributes, t) {
const link = document.createElement('link');
link.rel = "preload";
Object.entries(attributes).forEach(([key, value]) => {
if (value)
link[key] = value;
});

document.head.appendChild(link);
t.add_cleanup(() => link.remove());
return new Promise(resolve => link.addEventListener('load', resolve));
}

const loaders = {
image: (href, attr, t) => {
const img = document.createElement('img');
Object.entries(attr).forEach(([key, value]) => {
img[key] = value;
});

img.src = href

document.body.appendChild(img);
t.add_cleanup(() => img.remove());
return new Promise(resolve => {
img.addEventListener('load', resolve);
img.addEventListener('error', resolve);
});
},
font: (href, attr, t) => {
const style = document.createElement('style');
style.innerHTML = `@font-face {
font-family: 'MyFont';
src: url('${href}');
}`;

document.head.appendChild(style);
t.add_cleanup(() => style.remove());
const p = document.createElement('p');
p.style.fontFamily = 'MyFont';
document.body.appendChild(p);
t.add_cleanup(() => p.remove());
},
shape: (href, attr, t) => {
const div = document.createElement('div');
div.style.shapeOutside = `url(${href})`;
document.body.appendChild(div);
t.add_cleanup(() => div.remove());
},
backgroundImage: (href, attr, t) => {
const div = document.createElement('div');
div.style.background = `url(${href})`;
document.body.appendChild(div);
t.add_cleanup(() => div.remove());
},
fetch: async (href, attr, t) => {
const options = {mode: attr.crossOrigin ? 'cors' : 'no-cors',
credentials: !attr.crossOrigin || attr.crossOrigin === 'anonymous' ? 'omit' : 'include'}

const response = await fetch(href, options)
await response.text();
},
script: async (href, attr, t) => {
const script = document.createElement('script');
t.add_cleanup(() => script.remove());
if (attr.crossOrigin)
script.setAttribute('crossorigin', attr.crossOrigin);
script.src = href;
document.body.appendChild(script);
await new Promise(resolve => { script.onload = resolve });
},
module: async (href, attr, t) => {
const script = document.createElement('script');
script.type = 'module';
t.add_cleanup(() => script.remove());
if (attr.crossOrigin)
script.setAttribute('crossorigin', attr.crossOrigin);
script.src = href;
document.body.appendChild(script);
await new Promise(resolve => { script.onload = resolve });
},
style: (href, attr, t) => {
const style = document.createElement('link');
style.rel = 'stylesheet';
t.add_cleanup(() => style.remove());
if (attr.crossOrigin)
style.setAttribute('crossorigin', attr.crossOrigin);
document.body.appendChild(style);
}
}

function preload_reuse_test(type, as, url, preloadConfig, resourceConfig) {
const expected = (preloadConfig === resourceConfig) ? "reuse" : "discard";
const key = token();
const href = getAbsoluteURL(`${
(configs[resourceConfig].crossOrigin ? HTTPS_REMOTE_ORIGIN : '') + url
}&${token()}`)
promise_test(async t => {
await preload({href, as, ...configs[preloadConfig].attributes}, t);
await loaders[as](href, configs[resourceConfig].attributes, t)
verifyNumberOfResourceTimingEntries(href, expected === "reuse" ? 1 : 2)
}, `Loading ${type} (${resourceConfig}) with link (${preloadConfig}) should ${expected} the preloaded response`);
}

for (const [resourceTypeName, resourceInfo] of Object.entries(resourceTypes)) {
const configNames = resourceInfo.config ? [resourceInfo.config, 'same-origin'] : Object.keys(configs)
for (const resourceConfigName of configNames) {
for (const preloadConfigName of Object.keys(configs)) {
// Same-origin requests ignore their CORS attributes, so no need to match all of them.
if ((resourceConfigName === 'same-origin' && preloadConfigName === 'same-origin') ||
(resourceConfigName !== 'same-origin' && preloadConfigName !== 'same-origin'))
preload_reuse_test(resourceTypeName, resourceInfo.as, resourceInfo.url, preloadConfigName, resourceConfigName);
}
}

}
</script>
8 changes: 8 additions & 0 deletions preload/resources/echo-with-cors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def main(request, response):
response.headers.set(b"Content-Type", request.GET.first(b"type"))
origin = request.headers.get('Origin')
if origin is not None:
response.headers.set(b"Access-Control-Allow-Origin", origin)
response.headers.set(b"Access-Control-Allow-Credentials", b"true")

return request.GET.first(b"content")
Binary file added preload/resources/font.ttf
Binary file not shown.
2 changes: 2 additions & 0 deletions preload/resources/font.ttf.sub.headers
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Access-Control-Allow-Origin: {{header_or_default(Origin, *)}}
Access-Control-Allow-Credentials: true