Skip to content

Commit

Permalink
add test
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickhulce committed Oct 13, 2017
1 parent dae25d2 commit 5b59b98
Show file tree
Hide file tree
Showing 2 changed files with 162 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lighthouse-core/audits/byte-efficiency/cache-headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ const STATIC_RESOURCE_TYPES = new Set([
const RESOURCE_AGE_IN_HOURS_DECILES = [0, 0.2, 1, 3, 8, 12, 24, 48, 72, 168, 8760, Infinity];

class CacheHeaders extends ByteEfficiencyAudit {
/**
* @return {number}
*/
static get WASTED_BYTES_DISCOUNT_MULTIPLIER() {
return WASTED_BYTES_DISCOUNT_MULTIPLIER;
}

/**
* @return {!AuditMeta}
*/
Expand Down Expand Up @@ -129,7 +136,7 @@ class CacheHeaders extends ByteEfficiencyAudit {
const expires = new Date(headers.get('expires')).getTime();
// Invalid expires values MUST be treated as already expired
if (!expires) return 0;
return Math.max(0, (Date.now() - expires) / 1000);
return Math.max(0, Math.ceil((expires - Date.now()) / 1000));
}

return null;
Expand Down
154 changes: 154 additions & 0 deletions lighthouse-core/test/audits/byte-efficiency/cache-headers-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

const CacheHeadersAudit = require('../../../audits/byte-efficiency/cache-headers.js');
const assert = require('assert');
const WebInspector = require('../../../lib/web-inspector');

/* eslint-env mocha */

function networkRecord(options = {}) {
const headers = [];
Object.keys(options.headers || {}).forEach(name => {
headers.push({name, value: options.headers[name]});
});

return {
_url: options.url || 'https://example.com/asset',
statusCode: options.statusCode || 200,
_resourceType: options.resourceType || WebInspector.resourceTypes.Script,
_transferSize: options.transferSize || 1000,
_responseHeaders: headers,
};
}

const DISCOUNT_MULTIPLIER = CacheHeadersAudit.WASTED_BYTES_DISCOUNT_MULTIPLIER;

describe('Cache headers audit', () => {
let artifacts;
let networkRecords;

beforeEach(() => {
artifacts = {
devtoolsLogs: {},
requestNetworkRecords: () => Promise.resolve(networkRecords),
requestNetworkThroughput: () => Promise.resolve(1000),
};
});

it('detects missing cache headers', () => {
networkRecords = [networkRecord()];
return CacheHeadersAudit.audit(artifacts).then(result => {
const items = result.extendedInfo.value.results;
assert.equal(items.length, 1);
assert.equal(items[0].cacheLifetimeInSeconds, 0);
assert.equal(items[0].wastedBytes, 1000 * DISCOUNT_MULTIPLIER);
});
});

it('detects low value max-age headers', () => {
networkRecords = [
networkRecord({headers: {'cache-control': 'max-age=3600'}}), // an hour
networkRecord({headers: {'cache-control': 'max-age=86400'}}), // a day
networkRecord({headers: {'cache-control': 'max-age=604800'}}), // a week
];

return CacheHeadersAudit.audit(artifacts).then(result => {
const items = result.extendedInfo.value.results;
assert.equal(items.length, 2);
assert.equal(items[0].cacheLifetimeInSeconds, 3600);
assert.equal(items[0].cacheLifetimeDisplay, '1\xa0h');
assert.equal(Math.round(items[0].wastedBytes), 1000 * .7 * DISCOUNT_MULTIPLIER);
assert.equal(items[1].cacheLifetimeDisplay, '1\xa0d');
assert.equal(Math.round(items[1].wastedBytes), 1000 * .3 * DISCOUNT_MULTIPLIER);
});
});

it('detects low value expires headers', () => {
const expiresIn = seconds => new Date(Date.now() + seconds * 1000).toGMTString();

networkRecords = [
networkRecord({headers: {expires: expiresIn(3600)}}), // an hour
networkRecord({headers: {expires: expiresIn(86400)}}), // a day
networkRecord({headers: {expires: expiresIn(604800)}}), // a week
];

return CacheHeadersAudit.audit(artifacts).then(result => {
const items = result.extendedInfo.value.results;
assert.equal(items.length, 2);
assert.ok(Math.abs(items[0].cacheLifetimeInSeconds - 3600) <= 1, 'invalid expires parsing');
assert.equal(Math.round(items[0].wastedBytes), 1000 * .7 * DISCOUNT_MULTIPLIER);
assert.ok(Math.abs(items[1].cacheLifetimeInSeconds - 86400) <= 1, 'invalid expires parsing');
assert.equal(Math.round(items[1].wastedBytes), 1000 * .3 * DISCOUNT_MULTIPLIER);
});
});

it('respects expires/cache-control priority', () => {
const expiresIn = seconds => new Date(Date.now() + seconds * 1000).toGMTString();

networkRecords = [
networkRecord({headers: {
'cache-control': 'must-revalidate,max-age=3600',
'expires': expiresIn(86400),
}}),
networkRecord({headers: {
'cache-control': 'private,must-revalidate',
'expires': expiresIn(86400),
}}),
];

return CacheHeadersAudit.audit(artifacts).then(result => {
const items = result.extendedInfo.value.results;
assert.equal(items.length, 2);
assert.ok(Math.abs(items[0].cacheLifetimeInSeconds - 3600) <= 1, 'invalid expires parsing');
assert.equal(Math.round(items[0].wastedBytes), 1000 * .7 * DISCOUNT_MULTIPLIER);
assert.ok(Math.abs(items[1].cacheLifetimeInSeconds - 86400) <= 1, 'invalid expires parsing');
assert.equal(Math.round(items[1].wastedBytes), 1000 * .3 * DISCOUNT_MULTIPLIER);
});
});

it('ignores explicit no-cache policies', () => {
networkRecords = [
networkRecord({headers: {expires: '-1'}}),
networkRecord({headers: {'cache-control': 'no-store'}}),
networkRecord({headers: {'cache-control': 'no-cache'}}),
networkRecord({headers: {'cache-control': 'max-age=0'}}),
networkRecord({headers: {pragma: 'no-cache'}}),
];

return CacheHeadersAudit.audit(artifacts).then(result => {
const items = result.extendedInfo.value.results;
assert.equal(items.length, 0);
});
});

it('ignores records with Etags', () => {
networkRecords = [
networkRecord({headers: {etag: 'md5hashhere'}}),
networkRecord({headers: {'etag': 'md5hashhere', 'cache-control': 'max-age=60'}}),
];

return CacheHeadersAudit.audit(artifacts).then(result => {
const items = result.extendedInfo.value.results;
assert.equal(items.length, 0);
});
});

it('ignores potentially uncacheable records', () => {
networkRecords = [
networkRecord({statusCode: 500}),
networkRecord({url: 'https://example.com/dynamic.js?userId=crazy'}),
networkRecord({url: 'data:image/jpeg;base64,what'}),
networkRecord({resourceType: WebInspector.resourceTypes.XHR}),
];

return CacheHeadersAudit.audit(artifacts).then(result => {
const items = result.extendedInfo.value.results;
assert.equal(items.length, 0);
});
});
});

0 comments on commit 5b59b98

Please sign in to comment.